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
and1
- we can only change
0
to1
and1
to0
- when we meet
1
in array, we have to change it to0
, 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
to0
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;
}