Fill 2-dimensional array with zeros by flipping groups of cells - c++

There is a problem where I need to fill an array with zeros, with the following assumptions:
in the array there can only be 0 and 1
we can only change 0 to 1 and 1 to 0
when we meet 1 in array, we have to change it to 0, such that its neighbours are also changed, for instance, for the array like the one below:
1 0 1
1 1 1
0 1 0
When we change element at (1,1), we then got the array like this:
1 1 1
0 0 0
0 0 0
We can't change the first row
We can only change the elements that are in the array
The final result is the number of times we have to change 1 to 0 to zero out the array
1) First example, array is like this one below:
0 1 0
1 1 1
0 1 0
the answer is 1.
2) Second example, array is like this one below:
0 1 0 0 0 0 0 0
1 1 1 0 1 0 1 0
0 0 1 1 0 1 1 1
1 1 0 1 1 1 0 0
1 0 1 1 1 0 1 0
0 1 0 1 0 1 0 0
The answer is 10.
There also can be situations that its impossible to zero out the array, then the answer should be "impossible".
Somehow I can't get this working: for the first example, I got the right answer (1) but for the second example, program says impossible instead of 10.
Any ideas what's wrong in my code?
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
int n,m;
cin >> n >> m;
bool tab[n][m];
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
cin >> tab[i][j];
int counter = 0;
for(int i=0; i<n-1; i++)
{
for(int j=0; j<m-1; j++)
{
if(tab[i][j] == 1 && i > 0 && j > 0)
{
tab[i-1][j] = !tab[i-1][j];
tab[i+1][j] = !tab[i+1][j];
tab[i][j+1] = !tab[i][j+1];
tab[i][j-1] = !tab[i][j-1];
tab[i][j] = !tab[i][j];
counter ++;
}
}
}
bool impossible = 0;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(tab[i][j] == 1)
{
cout << "impossible\n";
impossible = 1;
break;
}
}
if(impossible)
break;
}
if(!impossible)
cout << counter << "\n";
return 0;
}

I believe that the reason your program was returning impossible in the 6x8 matrix is because you have been traversing in a left to right / top to bottom fashion, replacing every instance of 1 you encountered with 0. Although this might have seemed as the right solution, all it did was scatter the 1s and 0s around the matrix by modifying it's neighboring values. I think that the way to approach this problem is to start from bottom to top/ right to left and push the 1s towards the first row. In a way cornering (trapping) them until they can get eliminated.
Anyway, here's my solution to this problem. I'm not entirely sure if this is what you were going after, but I think it does the job for the three matrices you provided. The code is not very sophisticated and it would be nice to test it with some harder problems to see if it truly works.
#include <iostream>
static unsigned counter = 0;
template<std::size_t M, std::size_t N>
void print( const bool (&mat) [M][N] )
{
for (std::size_t i = 0; i < M; ++i)
{
for (std::size_t j = 0; j < N; ++j)
std::cout<< mat[i][j] << " ";
std::cout<<std::endl;
}
std::cout<<std::endl;
}
template<std::size_t M, std::size_t N>
void flipNeighbours( bool (&mat) [M][N], unsigned i, unsigned j )
{
mat[i][j-1] = !(mat[i][j-1]);
mat[i][j+1] = !(mat[i][j+1]);
mat[i-1][j] = !(mat[i-1][j]);
mat[i+1][j] = !(mat[i+1][j]);
mat[i][j] = !(mat[i][j]);
++counter;
}
template<std::size_t M, std::size_t N>
bool checkCornersForOnes( const bool (&mat) [M][N] )
{
return (mat[0][0] || mat[0][N-1] || mat[M-1][0] || mat[M-1][N-1]);
}
template<std::size_t M, std::size_t N>
bool isBottomTrue( bool (&mat) [M][N], unsigned i, unsigned j )
{
return (mat[i+1][j]);
}
template<std::size_t M, std::size_t N>
bool traverse( bool (&mat) [M][N] )
{
if (checkCornersForOnes(mat))
{
std::cout<< "-Found 1s in the matrix corners." <<std::endl;
return false;
}
for (std::size_t i = M-2; i > 0; --i)
for (std::size_t j = N-2; j > 0; --j)
if (isBottomTrue(mat,i,j))
flipNeighbours(mat,i,j);
std::size_t count_after_traversing = 0;
for (std::size_t i = 0; i < M; ++i)
for (std::size_t j = 0; j < N; ++j)
count_after_traversing += mat[i][j];
if (count_after_traversing > 0)
{
std::cout<< "-Found <"<<count_after_traversing<< "> 1s in the matrix." <<std::endl;
return false;
}
return true;
}
#define MATRIX matrix4
int main()
{
bool matrix1[3][3] = {{1,0,1},
{1,1,1},
{0,1,0}};
bool matrix2[3][3] = {{0,1,0},
{1,1,1},
{0,1,0}};
bool matrix3[5][4] = {{0,1,0,0},
{1,0,1,0},
{1,1,0,1},
{1,1,1,0},
{0,1,1,0}};
bool matrix4[6][8] = {{0,1,0,0,0,0,0,0},
{1,1,1,0,1,0,1,0},
{0,0,1,1,0,1,1,1},
{1,1,0,1,1,1,0,0},
{1,0,1,1,1,0,1,0},
{0,1,0,1,0,1,0,0}};
std::cout<< "-Problem-" <<std::endl;
print(MATRIX);
if (traverse( MATRIX ) )
{
std::cout<< "-Answer-"<<std::endl;
print(MATRIX);
std::cout<< "Num of flips = "<<counter <<std::endl;
}
else
{
std::cout<< "-The Solution is impossible-"<<std::endl;
print(MATRIX);
}
}
Output for matrix1:
-Problem-
1 0 1
1 1 1
0 1 0
-Found 1s in the matrix corners.
-The Solution is impossible-
1 0 1
1 1 1
0 1 0
Output for matrix2:
-Problem-
0 1 0
1 1 1
0 1 0
-Answer-
0 0 0
0 0 0
0 0 0
Num of flips = 1
Output for matrix3:
-Problem-
0 1 0 0
1 0 1 0
1 1 0 1
1 1 1 0
0 1 1 0
-Found <6> 1s in the matrix.
-The Solution is impossible-
0 1 1 0
1 0 1 1
0 0 0 0
0 0 0 1
0 0 0 0
Output for matrix4 (which addresses your original question):
-Problem-
0 1 0 0 0 0 0 0
1 1 1 0 1 0 1 0
0 0 1 1 0 1 1 1
1 1 0 1 1 1 0 0
1 0 1 1 1 0 1 0
0 1 0 1 0 1 0 0
-Answer-
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Num of flips = 10

Ok, here comes my somewhat different attempt.
Idea
Note: I assume here that "We can't change the first row" means "We can't change the outmost row".
Some terminology:
With toggling a bit I mean changing it's value from 0 to 1 or 1 to 0.
With flipping a bit I mean toggling said bit and the 4 bits around it.
The act of toggling a bit is commutative. That is, it does not matter in what order we toggle it—the end result will always be the same (this is a trivial statement). This means that flipping is also a commutative action, and we are free to flip bits in any order we like.
The only way to toggle a value on the edge of the matrix is by flipping the bit right next to it an uneven amount of times. As we're looking for the lowest possible flips, we want to flip it a maximum of 1 time. So, in a scenario like the on below, x will need to be flipped exactly once, and y will need to be flipped exactly 0 times.
. .
1 x
0 y
. ,
From this we can draw two conclusions:
A corner of the matrix can never be toggled—if a 1 on the corner is found it is not possible with any number of flips to make the matrix zero. Your first example can thus be discarded without even flipping a single bit.
A bit next to a corner must have the same same value as the bit on the other side. This matrix that you posted in a comment can thus as well be discarded without flipping a single bit (bottom right corner).
Two examples of the conditions above:
0 1 .
0 x .
. . .
Not possible, as x needs to be flipped exactly once and exactly zero times.
0 1 .
1 x .
. . .
Possible, x needs to be flipped exactly once.
Algorithm
We can now make an recursive argument, and I propose the following:
We are given an m by n matrix.
Check the corner conditions above as stated above (i.e. corner != 1, bits next to corner has to be the same value). If either criteria are violated, return impossible.
Go around the edge of the matrix. If a 1 is encountered, flip the closest bit inside, and add 1 to the counter.
Restart now from #1 with a m - 2 by n - 2 matrix (top and bot row removed, left and right column) if either dimension is > 2, otherwise print the counter and quit.
Implementation
Initially I had thought this would turn out nice and pretty, but truth be told it is a little more cumbersome than I originally thought it would be as we have to keep track of a lot of indices. Please ask questions if you're wondering about the implementation, but it is in essence a pure translation of the steps above.
#include <iostream>
#include <vector>
using Matrix = std::vector<std::vector<int>>;
void flip_bit(Matrix& mat, int i, int j, int& counter)
{
mat[i][j] = !mat[i][j];
mat[i - 1][j] = !mat[i - 1][j];
mat[i + 1][j] = !mat[i + 1][j];
mat[i][j - 1] = !mat[i][j - 1];
mat[i][j + 1] = !mat[i][j + 1];
++counter;
}
int flip(Matrix& mat, int n, int m, int p = 0, int counter = 0)
{
// I use p for 'padding', i.e. 0 means the full array, 1 means the outmost edge taken away, 2 the 2 most outmost edges, etc.
// max indices of the sub-array
int np = n - p - 1;
int mp = m - p - 1;
// Checking corners
if (mat[p][p] || mat[np][p] || mat[p][mp] || mat[np][mp] || // condition #1
(mat[p + 1][p] != mat[p][p + 1]) || (mat[np - 1][p] != mat[np][p + 1]) || // condition #2
(mat[p + 1][mp] != mat[p][mp - 1]) || (mat[np - 1][mp] != mat[np][mp - 1]))
return -1;
// We walk over all edge values that are *not* corners and
// flipping the bit that are *inside* the current bit if it's 1
for (int j = p + 1; j < mp; ++j) {
if (mat[p][j]) flip_bit(mat, p + 1, j, counter);
if (mat[np][j]) flip_bit(mat, np - 1, j, counter);
}
for (int i = p + 1; i < np; ++i) {
if (mat[i][p]) flip_bit(mat, i, p + 1, counter);
if (mat[i][mp]) flip_bit(mat, i, mp - 1, counter);
}
// Finished or flip the next sub-array?
if (np == 1 || mp == 1)
return counter;
else
return flip(mat, n, m, p + 1, counter);
}
int main()
{
int n, m;
std::cin >> n >> m;
Matrix mat(n, std::vector<int>(m, 0));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
std::cin >> mat[i][j];
}
}
int counter = flip(mat, n, m);
if (counter < 0)
std::cout << "impossible" << std::endl;
else
std::cout << counter << std::endl;
}
Output
3 3
1 0 1
1 1 1
0 1 0
impossible
3 3
0 1 0
1 1 1
0 1 0
1
6 8
0 1 0 0 0 0 0 0
1 1 1 0 1 0 1 0
0 0 1 1 0 1 1 1
1 1 0 1 1 1 0 0
1 0 1 1 1 0 1 0
0 1 0 1 0 1 0 0
10
4 6
0 1 0 0
1 0 1 0
1 1 0 1
1 1 1 0
1 1 1 0
impossible

If tab[0][j] is 1, you have to toggle tab[1][j] to clear it. You then cannot toggle row 1 without unclearing row 0. So it seems like a reduction step. You repeat the step until there is one row left. If that last row is not clear by luck, my intuition is that it's the "impossible" case.
#include <memory>
template <typename Elem>
class Arr_2d
{
public:
Arr_2d(unsigned r, unsigned c)
: rows_(r), columns_(c), data(new Elem[rows_ * columns_]) { }
Elem * operator [] (unsigned row_idx)
{ return(data.get() + (row_idx * columns_)); }
unsigned rows() const { return(rows_); }
unsigned columns() const { return(columns_); }
private:
const unsigned rows_, columns_;
std::unique_ptr<Elem []> data;
};
inline void toggle_one(bool &b) { b = !b; }
void toggle(Arr_2d<bool> &tab, unsigned row, unsigned column)
{
toggle_one(tab[row][column]);
if (column > 0)
toggle_one(tab[row][column - 1]);
if (row > 0)
toggle_one(tab[row - 1][column]);
if (column < (tab.columns() - 1))
toggle_one(tab[row][column + 1]);
if (row < (tab.rows() - 1))
toggle_one(tab[row + 1][column]);
}
int solve(Arr_2d<bool> &tab)
{
int count = 0;
unsigned i = 0;
for ( ; i < (tab.rows() - 1); ++i)
for (unsigned j = 0; j < tab.columns(); ++j)
if (tab[i][j])
{
toggle(tab, i + 1, j);
++count;
}
for (unsigned j = 0; j < tab.columns(); ++j)
if (tab[i][j])
// Impossible.
return(-count);
return(count);
}
unsigned ex1[] = {
0, 1, 0,
1, 1, 1,
0, 1, 0
};
unsigned ex2[] = {
0, 1, 0, 0, 0, 0, 0, 0,
1, 1, 1, 0, 1, 0, 1, 0,
0, 0, 1, 1, 0, 1, 1, 1,
1, 1, 0, 1, 1, 1, 0, 0,
1, 0, 1, 1, 1, 0, 1, 0,
0, 1, 0, 1, 0, 1, 0, 0
};
Arr_2d<bool> load(unsigned rows, unsigned columns, const unsigned *data)
{
Arr_2d<bool> res(rows, columns);
for (unsigned i = 0; i < rows; ++i)
for (unsigned j = 0; j < columns; ++j)
res[i][j] = !!*(data++);
return(res);
}
#include <iostream>
int main()
{
{
Arr_2d<bool> tab = load(3, 3, ex1);
std::cout << solve(tab) << '\n';
}
{
Arr_2d<bool> tab = load(6, 8, ex2);
std::cout << solve(tab) << '\n';
}
return(0);
}

The problem is stated like this:
y
yxy If you flip x, then you have to flip all the ys
y
But it's easy if you think about it like this:
x
yyy If you flip x, then you have to flip all the ys
y
It's the same thing, but now the solution is obvious -- You must flip all the 1s in row 0, which will flip some bits in rows 1 and 2, then you must flip all the 1s in row 1, etc, until you get to the end.

If this is indeed the Lights Out game, then there are plenty of resources that detail how to solve the game. It is also quite likely that this is a duplicate of Lights out game algorithm, as has already been mentioned by other posters.
Let's see if we can't solve the first sample puzzle provided, however, and at least present a concrete description of an algorithm.
The initial puzzle appears to be solvable:
1 0 1
1 1 1
0 1 0
The trick is that you can clear 1's in the top row by changing the values in the row underneath them. I'll provide coordinates by row and column, using a 1-based offset, meaning that the top left value is (1, 1) and the bottom right value is (3, 3).
Change (2, 1), then (2, 3), then (3, 2). I'll show the intermediate states of the board with the * for the cell being changed in the next step.
1 0 1 (2,1) 0 0 1 (2,3) 0 0 0 (3, 2) 0 0 0
* 1 1 ------> 0 0 * ------> 0 1 0 ------> 0 0 0
0 1 0 1 1 0 1 * 1 0 0 0
This board can be solved, and the number of moves appears to be 3.
The pseudo-algorithm is as follows:
flipCount = 0
for each row _below_ the top row:
for each element in the current row:
if the element in the row above is 1, toggle the element in this row:
increment flipCount
if the board is clear, output flipCount
if the board isnt clear, output "Impossible"
I hope this helps; I can elaborate further if required but this is the core of the standard lights out solution. BTW, it is related to Gaussian Elimination; linear algebra crops up in some odd situations :)
Finally, in terms of what is wrong with your code, it appears to be the following loop:
for(int i=0; i<n-1; i++)
{
for(int j=0; j<m-1; j++)
{
if(tab[i][j] == 1 && i > 0 && j > 0)
{
tab[i-1][j] = !tab[i-1][j];
tab[i+1][j] = !tab[i+1][j];
tab[i][j+1] = !tab[i][j+1];
tab[i][j-1] = !tab[i][j-1];
tab[i][j] = !tab[i][j];
counter ++;
}
}
}
Several issues occur to me, but first assumptions again:
i refers to the ith row and there are n rows
j refers to the jth column and there are m columns
I'm now referring to indices that start from 0 instead of 1
If this is the case, then the following is observed:
You could run your for i loop from 1 instead of 0, which means you no longer have to check whether i > 0 in the if statement
You should drop the for j > 0 in the if statement; that check means that you can't flip anything in the first column
You need to change the n-1 in the for i loop as you need to run this for the final row
You need to change the m-1 in the for j loop as you need to run this for the final column (see point 2 also)
You need to check the cell in the row above the current row, so you you should be checking tab[i-1][j] == 1
Now you need to add bounds tests for j-1, j+1 and i+1 to avoid reading outside valid ranges of the matrix
Put these together and you have:
for(int i=1; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(tab[i-1][j] == 1)
{
tab[i-1][j] = !tab[i-1][j];
if (i+1 < n)
tab[i+1][j] = !tab[i+1][j];
if (j+1 < m)
tab[i][j+1] = !tab[i][j+1];
if (j > 0)
tab[i][j-1] = !tab[i][j-1];
tab[i][j] = !tab[i][j];
counter ++;
}
}
}

A little class that can take as a input file or test all possible combination for first row with only zeros, on 6,5 matrix:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
typedef std::vector< std::vector<int> > Matrix;
class MatrixCleaner
{
public:
void swapElement(int row, int col)
{
if (row >= 0 && row < (int)matrix.size() && col >= 0 && col < (int)matrix[row].size())
matrix[row][col] = !matrix[row][col];
}
void swapElements(int row, int col)
{
swapElement(row - 1, col);
swapElement(row, col - 1);
swapElement(row, col);
swapElement(row, col + 1);
swapElement(row + 1, col);
}
void printMatrix()
{
for (auto &v : matrix)
{
for (auto &val : v)
{
std::cout << val << " ";
}
std::cout << "\n";
}
}
void loadMatrix(std::string path)
{
std::ifstream fileStream;
fileStream.open(path);
matrix.resize(1);
bool enconteredNumber = false;
bool skipLine = false;
bool skipBlock = false;
for (char c; fileStream.get(c);)
{
if (skipLine)
{
if (c != '*')
skipBlock = true;
if (c != '\n')
continue;
else
skipLine = false;
}
if (skipBlock)
{
if (c == '*')
skipBlock = false;
continue;
}
switch (c)
{
case '0':
matrix.back().push_back(0);
enconteredNumber = true;
break;
case '1':
matrix.back().push_back(1);
enconteredNumber = true;
break;
case '\n':
if (enconteredNumber)
{
matrix.resize(matrix.size() + 1);
enconteredNumber = false;
}
break;
case '#':
if(!skipBlock)
skipLine = true;
break;
case '*':
skipBlock = true;
break;
default:
break;
}
}
while (matrix.size() > 0 && matrix.back().empty())
matrix.pop_back();
fileStream.close();
}
void loadRandomValidMatrix(int seed = -1)
{
//Default matrix
matrix = {
{ 0,0,0,0,0 },
{ 0,0,0,0,0 },
{ 0,0,0,0,0 },
{ 0,0,0,0,0 },
{ 0,0,0,0,0 },
{ 0,0,0,0,0 },
};
int setNum = seed;
if(seed < 0)
if(seed < -1)
setNum = std::rand() % -seed;
else
setNum = std::rand() % 33554432;
for (size_t r = 1; r < matrix.size(); r++)
for (size_t c = 0; c < matrix[r].size(); c++)
{
if (setNum & 1)
swapElements(r, c);
setNum >>= 1;
}
}
bool test()
{
bool retVal = true;
for (int i = 0; i < 33554432; i++)
{
loadRandomValidMatrix(i);
if( (i % 1000000) == 0 )
std::cout << "i= " << i << "\n";
if (clean() < 0)
{
// std::cout << "x";
std::cout << "\n" << i << "\n";
retVal = false;
break;
}
else
{
// std::cout << ".";
}
}
return retVal;
}
int clean()
{
int numOfSwaps = 0;
try
{
for (size_t r = 1; r < matrix.size(); r++)
{
for (size_t c = 0; c < matrix[r].size(); c++)
{
if (matrix.at(r - 1).at(c))
{
swapElements(r, c);
numOfSwaps++;
}
}
}
}
catch (...)
{
return -2;
}
if (!matrix.empty())
for (auto &val : matrix.back())
{
if (val == 1)
{
numOfSwaps = -1;
break;
}
}
return numOfSwaps;
}
Matrix matrix;
};
int main(int argc, char **argv)
{
std::srand(std::time(NULL));
MatrixCleaner matrixSwaper;
if (argc > 1)
{
matrixSwaper.loadMatrix(argv[argc - 1]);
std::cout << "intput:\n";
matrixSwaper.printMatrix();
int numOfSwaps = matrixSwaper.clean();
std::cout << "\noutput:\n";
matrixSwaper.printMatrix();
if (numOfSwaps > 0)
std::cout << "\nresult = " << numOfSwaps << " matrix is clean now " << std::endl;
else if (numOfSwaps == 0)
std::cout << "\nresult = " << numOfSwaps << " nothing to clean " << std::endl;
else
std::cout << "\nresult = " << numOfSwaps << " matrix cannot be clean " << std::endl;
}
else
{
std::cout << "Testing ";
if (matrixSwaper.test())
std::cout << " PASS\n";
else
std::cout << " FAIL\n";
}
std::cin.ignore();
return 0;
}

Related

Generate all undirected graphs with n nodes

I'm trying to generate all the undirected graphs with n nodes, using recursive backtracking. I have to write their matrix (I don't know how is it called in english - in my language it would be adjacent matrix - is that right?) into a file.
For example:
input
3
output
8
0 0 0
0 0 0
0 0 0
0 0 0
0 0 1
0 1 0
0 0 1
0 0 0
1 0 0
0 0 1
0 0 1
1 1 0
0 1 0
1 0 0
0 0 0
0 1 0
1 0 1
0 1 0
0 1 1
1 0 0
1 0 0
0 1 1
1 0 1
1 1 0
Here is my program:
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("gengraf.in");
ofstream g("gengraf.out");
int st[100], n, adiacenta[100][100], l=1;
void tipar(int k)
{
for (int i = 1; i < k; i++)
{
for (int j = i+1; j < k; j++)
{
adiacenta[i][j] = adiacenta[j][i] = st[l];
}
l++;
}
for (int i = 1; i < k; i++)
{
for (int j = 1; j < k; j++)
{
g << adiacenta[i][j] << " ";
}
g << endl;
}
}
int valid(int k)
{
return 1;
}
void back(int k)
{
if (k == ((n - 1) * n / 2) + 1)
{
l = 1;
tipar(k);
g << endl;
}
else
{
for (int i = 0; i <= 1; i++)
{
st[k] = i;
if (valid(k))
{
back(k + 1);
}
}
}
}
int main()
{
f >> n;
g << pow(2, (n * (n - 1))/2);
g << endl;
back(1);
}
but my output is:
8
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 1
0 1 0
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 0
0 1 1
1 0 0
1 0 0
0 1 1
1 0 1
1 1 0
0 1 1
1 0 1
1 1 0
and I don't know how to fix that.
I see why does happen - I generate 2^(n*(n-1))/2) graphs (because that's how many undirected graphs with n nodes are), and instead of generating 8 distinct ones, I get only 4 distinct ones, shown 2 times.
That is (I suppose) because my program outputs a graph with, let's say, a link between the node 1 and 3 and another graph with a link between the node 3 and 1. And that is basically the same undirected graph.
So if I am right, I should make my program not show each graph twice and it should work. So basically I have to get rid of each graph with the "reversed" node (so if I got one with a link between 1 and 3, I shouldn't get another one with a link between 3 and 1 because they are the same).
Am I right?
If so, how can I do that?
Thanks.
Problems with your code:
Value of l in tipar() id not increased after assignment.
Size of adjacency matrix is n * n not k * k.
This code work as expected.
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("gengraf.in");
ofstream g("gengraf.out");
int st[100], n, adiacenta[100][100], l=1;
int pow(int a, int b) {
int r = 1;
while (b) {
if (b&1) r *= a;
b >>= 1;
a *= a;
}
return r;
}
void tipar()
{
for (int i = 1; i <= n; i++)
{
for (int j = i+1; j <= n; j++)
{
adiacenta[i][j] = adiacenta[j][i] = st[l];
l++;
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
g << adiacenta[i][j] << " ";
}
g << endl;
}
}
int valid(int k)
{
return 1;
}
void back(int k)
{
if (k == (n * (n-1) / 2) + 1)
{
l = 1;
tipar();
g << endl;
}
else
{
for (int i = 0; i <= 1; i++)
{
st[k] = i;
if (valid(k))
{
back(k+1);
}
}
}
}
int main()
{
cin >> n;
g << pow(2, (n * (n - 1))/2);
g << endl;
back(1);
}

Path planning using 2D array

The problem require user input the size of 2D grid. Then input each of the entries.
Like this:
5 5
-1 -1 -1 -1 -1
-1 0 0 0 -1
-1 1 -1 0 -1
-1 0 0 -2 -1
-1 -1 -1 -1 -1
Then the output should be 3. Which is the smallest path from the starting point " 1 " to end point "-2". Where the " -1 " are the obstacle, 0 as a feasible space.
The method given by the instructor is:
first, locate the starting point " 1 " . The filling its feasible space 4-neighbours ( left, right, up and down) with " 2 "
Then, repeat the steps by filling the neighbours feasible space by " 3 " and so on.
When the possible feasible space is " -2 ". Stop and print out the minimum steps number.
I will try to write it out.
Find the starting point.
-1 -1 -1 -1 -1
-1 0 0 0 -1
-1 **1** -1 0 -1
-1 0 0 -2 -1
-1 -1 -1 -1 -1
Replace it neighbours "0" by " 2 " and find the other possible feasible space.
-1 -1 -1 -1 -1
-1 **2** **0** 0 -1
-1 1 -1 0 -1
-1 **2** **0** -2 -1
-1 -1 -1 -1 -1
Repeat the steps.
-1 -1 -1 -1 -1
-1 2 3 **0** -1
-1 1 -1 0 -1
-1 2 3 **-2** -1
-1 -1 -1 -1 -1
As the neighbour is " -2 " . So the shortest path is 3.
// Find the Starting point " 1 ".
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
///////// DO NOT MODIFY ANYTHING ABOVE THIS LINE /////////
// IMPORTANT: Do NOT change any of the function headers already provided to you
// It means that you will need to use the function headers as is
// You may implement additional functions here
bool NextFill(int(&map)[MAX_SIZE][MAX_SIZE], int n)
{
const int offx = { -1, 0, 0, 1 };
const int offy = { 0, -1, 1, 0 }
bool found = false;
for (int x = 0; x != MAX_SIZE; ++x) {
for (int y = 0; y != MAX_SIZE; ++y) {
if (map[x][y] == n) {
for (int i = 0; i != 4) {
auto& neighbor = map[x + offx[i]][y + offy[i]];
if (neighbor == -1) { }
else if (neighbor == -2) { found = true; }
else if (neighbor == 0) { neighbor = n + 1; }
}
}
}
}
return found;
}
// Function: find the smallest number of steps to go from the starting point
// to the destination in a given map.
//
// Input: int map[][]: 2D-array map
// int map_h: the height of the map
// int map_w: the width of the map
// Output: return true if a path is found, and store the smallest number of
// steps taken in &num_steps (pass-by-reference)
// return false if there is no path
// ==============================================================
bool FindPath(int map[][MAX_SIZE], int map_h, int map_w, int& num_steps)
{
// ==========================
int time = 0;
if (NextFill(map, time))
return true;
else
return false;
}
///////// DO NOT MODIFY ANYTHING BELOW THIS LINE /////////
// Function: main function
// ==============================================================
int main()
{
int map_h;
int map_w;
cin >> map_h >> map_w;
int map[MAX_SIZE][MAX_SIZE];
// initialize map
for (int i = 0; i < MAX_SIZE; i++)
for (int j = 0; j < MAX_SIZE; j++)
map[i][j] = -1;
// read map from standard input
for (int i = 0; i < map_h; i++)
for (int j = 0; j < map_w; j++)
cin >> map[i][j];
int steps;
// print to screen number of steps if a path is found, otherwise print "No"
if (FindPath(map, map_h, map_w, steps))
cout << steps << endl;
else
cout << "No" << endl;
}
My code can find the starting point and find its possible feasible space as well as replace it by " 2 ". But i have no idea of find the possible feasible space of mine " 2 " and replace it by " 3 " and so on.
However, I can't include any header in my program.
Thanks for reading a long long question :)!
You have either to store in some queue your open nodes, or fill from whole map each time:
bool NextFill(int (&map)[MAX_SIZE][MAX_SIZE], int n)
{
const int offx = {-1, 0, 0, 1};
const int offy = {0, -1, 1, 0}
bool found = false;
for (int x = 0; x != MAX_SIZE; ++x) {
for (int y = 0; y != MAX_SIZE; ++y) {
if (map[x][y] == n) {
for (int i = 0; i != 4) {
auto& neighbor = map[x + offx[i]][y + offy[i]];
if (neighbor == -1) { /*Nothing*/ } // wall
else if (neighbor == -2) { found = true; } // Found
else if (neighbor == 0) { neighbor = n + 1; } // unvisited
// else {/*Nothing*/} // Already visited.
}
}
}
}
return found;
}

How to make the line to be closed, having points of it? (in array)

I have a problem, I need to make the line to be closed, for example:
I put into the console this:
4
0 0
1 1
1 0
0 1
and it must return LIKE THIS:
0 0
0 1
1 1
1 0
NOT like this:
0 0
0 1
1 0
1 1
in other words:
I input the number of points, then I input coord_x and coord_y, then I need to sort them and also to make it closed
here is the code
struct Point {
int coordX;
int coordY;
};
for (int i = 1; i < sizeOfMasPoint; ++i) {
Point temp = masPoint[i];
bool is_Sorted = 0;
int j = i;
for (; j > 0; --j) {
if (temp.coordX > masPoint[j - 1].coordX) {
is_Sorted = 1;
} else {
if (temp.coordX < masPoint[j - 1].coordX) {
masPoint[j] = masPoint[j - 1];
} else {
if (temp.coordY >= masPoint[j - 1].coordY) {
is_Sorted = 1;
} else {
masPoint[j] = masPoint[j - 1];
}
}
}
if (is_Sorted == 1)
break;
}
masPoint[j] = temp;
}
it always returns this:
0 0
0 1
1 0
1 1
I need to make it closed...I don't know how
Thank you in advance!!!

c++ creating filled sudoku grid from empty matrix of size n

I'm trying to write a program that creates a matrix of size N, and puts numbers in so that no numbers repeat in the same column/row using backtracking.
1) Put value in cell. If it's a repeat, try a different value.
2) If no such value exists, backtrack 1 cell, and change the value. //recursive
However, the highest number repeats a few times sometimes. E.g:
3 1 2 3 1 2 4 5 2 4 1 3 6 5
1 3 3 2 3 1 5 4 4 3 2 5 1 6
2 3 1 1 2 5 3 5 < 1 5 3 2 4 6
4 5 3 1 2 5 1 6 4 2 3
5 4 5 2 1 < 6 2 4 1 3 6 <
^ 3 6 5 6 6 4 <
^
And here's what it's doing:
Once it runs out of numbers to put into a cell (i.e: all restricted, it puts N in)
3 1 2 4 3 1 2 4 3 1 2 4 3 1 2 4
1 2 3 0 -> 1 2 3 3 -> 1 2 3 4 -> 1 2 3 4
0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
I'm really stuck here, hopefully someone can find the error in my code:
int **grid; //2d dynamic array of size 'size'
bool checkRepeat(size,**grid,row,column); //checks if a number in a column/row is a repeat
int backtrack = 0;
int holder = 0; //when backtracking, this holds the number that should be changed
bool checkRepeat(int x, int** grid, int row, int col){
for (int i = 0; i < x; i++){
if (grid[row][col] == grid[row][i] && col != i){
return true;
}
}
for (int j = 0; j < x; j++){
if (grid[row][col] == grid[j][col] && row != j){
return true;
}
}
return false;
}
int main(){
for (int row = 0; row < size; row++){
for (int col = 0; col < size; col++){
if (backtrack == 0){
grid[row][col] = rand() % size + 1;
}
if (backtrack == 1){ //If backtracking, go back one cell.
grid[row][col] = 0; //(Since the above for loops went one
if (col == 0){ //cell forward, go 2 cells back)
col = size - 2;
row--;
} else if (col == 1){
col = size - 1;
row--;
} else {
col-=2;
}
holder = grid[row][col]; //put the current number into holder to avoid it
backtrack = 0;
}
/*the following checks if the number in the current cell is
a repeat and makes sure the number isn't the same as
before (holder). Then it checks all possible numbers (1 to size)
and puts one that matches the rules. If one is not found,
program backtracks 1 cell*/
if (checkRepeat(size,grid,row,col) && grid[row][col] > 0){
for (int x = 1; x < size+1 && (checkRepeat(x,grid,row,col) || holder == grid[row][col]); x++){
grid[row][col] = x;
}
}
if (grid[row][col] == checkRepeat(size,grid,row,col) || grid[row][col] == holder){
backtrack = 1; //if no valid number was found in the above
grid[row][col] = 0;
}
holder = 0;
}
}
So I may have gone a little overboard on the solution but I thought it was a good challenge for me. The basic idea is that fill(row, col) is a recursive function. First it checks the stopping conditions: if the filled-out part of the grid is not valid (a number is repeated in a row or column) it will return false. It will also return false if there's an attempt to fill outside the grid's size.
If neither stopping condition is met, it will try a value for the grid element and attempt to "fill the rest of the grid" (aka call the fn recursively). It will do those things as long as the "fill rest" operation fails and it hasn't tried all valid values. If it has tried all the valid values and the "fill rest" operation still fails, it resets the value to 0. Finally it returns whether the "fill rest" operation failed or succeeded.
#include <vector>
#include <iostream>
#include <cstdlib>
#include <numeric>
#include <time.h>
#include <string>
#include <sstream>
using std::vector;
// helper for std::accumulate
bool logical_and(bool x, bool y) {
return x & y;
}
class Grid {
public:
typedef int ElementType;
typedef vector< vector<ElementType> > GridElements;
Grid(const int linesize) :
linesize_(linesize)
{
srand(time(NULL));
// resizes to linesize_ rows & columns, with initial values == 0
gridElements_.resize(linesize_, vector<ElementType>(linesize_, 0));
}
// use like this: cout << grid.to_s();
std::string to_s() const {
std::stringstream ss;
for (int row = 0; row < gridElements_.size(); row++) {
for (int col = 0; col < gridElements_[row].size(); col++) {
ss << gridElements_[row][col] << " ";
}
ss << std::endl;
}
ss << std::endl;
return ss.str();
}
// return true if there are no repeated numbers within filled elements in
// rows/columns, false otherwise
bool isValid() const {
// you would also need to write and call a checkSquare method if you're doing a sudoku puzzle
for (int i = 0; i < linesize_; i++) {
if (!isRowValid(i) || !isColValid(i)) {
return false;
}
}
return true;
}
// the recursive function that actually puts values in the grid elements
// max recursion depth (I think) is linesize_^2
bool fill(int row, int col) {
// stopping conditions
if (!isValid()) {
return false;
}
if ((row == linesize_) || (col == linesize_)) {
return true;
}
int nextCol = (col + 1) % linesize_;
int nextRow = row;
if (nextCol < col) {
nextRow++;
}
// keep a record of what numbers have been tried in this element
vector<bool> attemptedNumbers(linesize_ + 1, false);
attemptedNumbers[0] = true;
// We will continue choosing values for gridElements_[row][col]
// as long as we haven't tried all the valid numbers, and as long as
// the rest of the grid is not valid with this choice
int value = 0;
bool triedAllNumbers = false;
bool restOfGridValid = false;
while (!triedAllNumbers && !restOfGridValid) {
while (attemptedNumbers[value]) {
value = rand() % linesize_ + 1;
}
attemptedNumbers[value] = true;
gridElements_[row][col] = value;
// uncomment this for debugging/intermediate grids
//std::cout << to_s();
// triedAllNumbers == true if all the numbers in [1, linesize_] have been tried
triedAllNumbers = std::accumulate(attemptedNumbers.begin(), attemptedNumbers.end(), true, logical_and);
restOfGridValid = fill(nextRow, nextCol);
}
if (triedAllNumbers && !restOfGridValid) {
// couldn't find a valid number for this location
gridElements_[row][col] = 0;
}
return restOfGridValid;
}
private:
// checks that a number is used only once in the row
// assumes that values in gridElements_ are in [1, linesize_]
// return false when the row contains repeated values, true otherwise
bool isRowValid(int row) const {
vector<bool> numPresent (linesize_ + 1, false);
for (int i = 0; i < linesize_; i++) {
int element = gridElements_[row][i];
if (element != 0) {
if (numPresent[element]) {
return false;
}
else {
numPresent[element] = true;
}
}
// don't do anything if element == 0
}
return true;
}
// checks that a number is used only once in the column
// assumes that values in gridElements_ are in [1, linesize_]
// return false when the column contains repeated values, true otherwise
bool isColValid(int col) const {
vector<bool> numPresent (linesize_ + 1, false);
for (int i = 0; i < linesize_; i++) {
int element = gridElements_[i][col];
if (element != 0) {
if (numPresent[element]) {
return false;
}
else {
numPresent[element] = true;
}
}
else {
// if element == 0, there isn't anything left to check, so just leave the loop
break;
}
}
return true;
}
// the size of each row/column
int linesize_;
// the 2d array
GridElements gridElements_;
};
int main(int argc, char** argv) {
// 6x6 grid
Grid grid(6);
// pretty sure this is mathematically guaranteed to always return true, assuming the algorithm is implemented correctly ;)
grid.fill(0, 0);
std::cout << grid.to_s();
}

Showing 2D array with one element at the time

I have a 2 dimensional array filled with 0s and 1s. I have to display that array in way that:
- 0s are always shown
- 1s are shown one at the time.
It suppose to look like a maze where 0 is a wall and 1 is a current position.
How can I do that in c++?
EDIT:
I came up with a solution but maybe there is simpler one. What if I'd create copy of my _array and copy 0s and blank spaces instead of 1s to it. Then in loop I'd assign one of _array "1" to second array then display whole array and then make swap 1 back with blank space?
EDIT2:
int _tmain(int argc, _TCHAR* argv[])
{
file();
int k=0,l=0;
for(int i=0;i<num_rows;i++)
{
for(int j=0;j<num_chars;j++)
{
if(_array[i][j] == 1)
{
k=i;
l=j;
break;
}
}
}
while(1)
{
for(int i=0;i<num_rows;i++)
{
for(int j=0;j<num_chars;j++)
{
if(_array[i][j] == 0) printf("%d",_array[i][j]);
else if(_array[i][j]==1)
{
if(k==i && l==j)
{
printf("1");
}
else printf(" ");
}
l++;
if(l>num_chars) break;
}
k++;
l=0;
printf("\n");
}
k=0;
system("cls");
}
return 0;
}
I wrote something like that but still i don't know how to clear screen in right moment. Function file() reads from file to 2D array.
Assuming you want something like that
000000
0 0
0000 0
0 1 0
0 0000
000000
You could print a 0 whenever it occurs and a blank space if not. To handle the current position you could use two additional variables like posX, posY. Now everytime you find a 1 in your array you check if (j == posX && i = posY) and print 1 if so...
As you just need to visualize the maze at different possible positions I'd propose a simple display function. DisplayMaze(int x, int y) is printing the maze in the required format to the screen. If _array[y][x] == 1 there is also printed a single 1...
void DisplayMaze(int x, int y)
{
for (int row = 0; row < num_rows; row++)
{
for (int col = 0; col < num_chars; col++)
{
if (_array[row][col] == 0)
std::cout << "0 ";
else if (row == y && col == x)
std::cout << "1 ";
else
std::cout << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
In order to display all possible positions you have to iterate over all of them and check if the current position is marked with 1 in the array (otherwise displaying would't make sense)
for (int y = 0; y < num_rows; y++)
{
for (int x = 0; x < num_chars; x++)
{
if (_array[y][x] == 1)
{
DisplayMaze(x, y);
}
}
}
The output should look like:
0 0 0 0 0 0
0 1 0
0 0 0 0 0
0 0
0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 1 0
0 0 0 0 0
0 0
0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 1 0
0 0 0 0 0
0 0
0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 1 0
0 0 0 0 0
0 0
0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0
0 0 0 0 1 0
0 0
0 0 0 0 0
0 0 0 0 0 0
...
However, i'd recommend a more C++ like approach as a maze could be implemented as a class. This class could bring it's own display-method and would encapsulate the internal data. It could basically look like:
class Maze
{
public:
// generate empty maze with given size
Maze(int width, int height);
// destructor
~Maze();
// print maze if the given position is marked with 1
void printPosition(int x, int y) const;
// takes a cstring as input to initialize the maze from
Maze& operator<<(const char* input);
// returns true if the given position is marked with 1
bool isValidPosition(int x, int y) const;
private:
// this is the actual representation of the maze
std::vector<std::vector<int> > grid_;
};
it would be used as followes:
Maze myMaze(num_chars, num_rows);
myMaze << "000000"
"011110"
"000010"
"011110"
"010000"
"000000";
for (int y = 0; y < num_rows; y++)
{
for (int x = 0; x < num_chars; x++)
{
if (myMaze.isValidPosition(x,y))
{
myMaze.printPosition(x,y);
}
}
}
hire you go*[solved]*
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int x,y;
cin>>x>>y;
char map[x][y];
memset(map, 'a', sizeof(map));
int y_pos = 0;
for (int x_pos = 0; x_pos < x * y; x_pos++){
if (x_pos == x){
x_pos = 0;
y_pos = y_pos + 1;
cout<<endl;
}
if (y_pos == y){
system("pause");
return 0;
}
cout<<map[x_pos][y_pos];
}