Wall destroying - c++

There is a wall built from numbers. 0 means there is a hole and blocks can't sit on holes. Someone has a special gun that fires all blocks with a number in one shot.
So I have a matrix called wall and have to write a gun. I wrote the program, but I have a problem and I do not understand why it is happening. In my code
#include <iostream>
#include <cstdio>
using namespace std;
int createWall( int &height, int &length, int wall[][ 100 ], int shots )
{
int i;
int j;
cin >> height;
cin >> length;
cin >> shots;
for ( i = 0; i < height; i++ )
{
for ( j = 0; j < length; j++ )
{
cin >> wall[ i ][ j ];
}
}
return shots;
}
void wallNow( int height, int length, int wall[][ 100 ] )
{
int i;
int j;
for ( i = 0; i < height; i++ )
{
for ( j = 0; j < length; j++ )
{
cout << wall[ i ][ j ] << " ";
}
cout << "\n";
}
}
void destroyWall( int height, int length, int wall[][100], int shots )
{
int i;
int j;
int k;
int x;
int aimedBlocks;//number to be "destroyed"
//set all aimedBlocks to 0
for ( x = 0; x < shots; x++ )
{
cin >> aimedBlocks;
for ( i = 0; i < height; i++ )
{
for ( k = 0; k < length; k++ )
{
if ( wall[ i ][ k ] == aimedBlocks )
{
wall[ i ][ k ] = 0;
}
}
}
}
int counter;//I use this variable because at some point I have a 0 followed only by 0's
for ( i = 0; i < length; i++ )
{
j = height - 1;
counter = 0;
//if I find a 0 then I move all elements higher that it one step down
while ( counter < height )
{
if ( wall[ j ][ i ] == 0 )
{
for ( k = j; k > 0; k-- )
{
wall[ k ][ i ] = wall[ k - 1 ][ i ];
}
wall[ height - j - 1 ][ i ] = 0;
}
else
j--;//I don't always go up ene step because the "block" droped in place of 0 may be 0
counter++;
}
}
}
int main()
{
int height;
int length;
int wall[ 100 ][ 100 ];
int shots = 0;
shots = createWall( height, length, wall, shots );
destroyWall( height, length, wall, shots );
wallNow( height, length, wall );
}
I really do not understand why line wall[ height - j - 1 ][ i ] = 0; is working for the first 4 columns in the following example and it does not work for the last one.
Format input:
height length shots
wall_0_0 ... wall_0_length
... ... ...
wall_height ... wall_height_length
shot_0 ... shot_shots
Input:
4 5 3
3 5 4 5 1
2 1 1 5 3
1 1 5 5 1
5 5 1 4 3
1 5 1
Remove all values that matches with 1, 5, 1. And wall remains must drop into the bottom.
Output:
0 0 0 0 0
0 0 0 0 0
3 0 0 0 0
2 0 4 4 3
Expected:
0 0 0 0 0
0 0 0 0 0
3 0 0 0 3
2 0 4 4 3
Please help me solve this problem. I could not find it debugging the code.

Your algorithm is strange, I don't understand what you try to do.
A simple way to achieve your purpose is to iterate from the left to the right of your wall, then for each you iterate from the bottom to the top. Each time you get a 0, you search for a non zero value to the top and swap their if you found it.
Example (very basic could be improve):
for (size_t i = 0; i < length; i++) { // i is for iterate from left(0) to right(length - 1)
size_t j = height; // j is for iterate from bot(height - 1) to top(0)
while (j-- > 0) {
if (wall[j][i] == 0) {
size_t k = j; // k is for found a non zero value from j - 1 to the top(0)
while (k-- > 0) {
if (wall[k][i] != 0) {
wall[j][i] = wall[k][i];
wall[k][i] = 0;
break;
}
}
}
}
}
Note:
I use size_t because this is the type for index.
I recommend you to switch for std::vector and use iterator on it in C++.

Related

How to transform an adjacency matrix into an incidence Matrix

I'm trying to transform the adjacency matrix into an incidence matrix of an undirected graph. For edges :
(1, 2), (1,5), (1,6), (2,3), (2,5), (3,4), (3,5), (4,5), (5,6)
Adj matrix is :
0 1 0 0 1 1
1 0 1 0 1 0
0 1 0 1 1 0
0 0 1 0 1 0
1 1 1 1 0 1
1 0 0 0 1 0
and I expect the result for the incidence matrix to be
0 1 0 0 1 1 0 0 0
1 0 1 0 1 0 0 0 0
0 1 0 1 1 0 0 0 0
0 0 1 0 1 0 0 0 0
1 1 1 1 0 1 0 0 0
1 0 0 0 1 0 0 0 0
but, my program returns this :
1 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 0 1 1 0 0 0 0
0 0 0 1 0 1 0 0 0
1 0 1 0 1 1 0 0 0
0 0 0 0 0 0 0 0 0
My source code :
graph constructor
Graph(int vertices, int edges)
{
this->vertices = vertices;
this->edges = edges;
edge = std::vector<Graph::Edge*>(edges);
for (int i = 0; i < edges; i++)
{
edge[i] = new Edge(this);
}
}
Graph* g = new Graph(numberOfVertices, numberOfEdges);
g->edge[0]->src = 1;
g->edge[0]->dest = 2;
g->edge[1]->src = 1;
g->edge[1]->dest = 5;
g->edge[2]->src = 1;
g->edge[2]->dest = 6;
g->edge[3]->src = 2;
g->edge[3]->dest = 3;
g->edge[4]->src = 2;
g->edge[4]->dest = 5;
g->edge[5]->src = 3;
g->edge[5]->dest = 4;
g->edge[6]->src = 3;
g->edge[6]->dest = 5;
g->edge[7]->src = 4;
g->edge[7]->dest = 5;
g->edge[8]->src = 5;
g->edge[8]->dest = 6;
for (i = 0; i < numberOfEdges; i++)
{
adjacency_matrix[g->edge[i]->src][g->edge[i]->dest] = 1;
adjacency_matrix[g->edge[i]->dest][g->edge[i]->src] = 1;
}
std::cout << "Adjacency matrix : " << std::endl;
for (i = 1; i <= numberOfVertices; i++)
{
for (j = 1; j <= numberOfVertices; j++)
{
std::cout<<adjacency_matrix[i][j]<<" ";
}
std::cout << std::endl;
}
// Incidence Matrix
int counter = 0;
for( int i = 1; i <= numberOfEdges; i++){
for(int j = i + 1; j < numberOfVertices; j++ ){
if(adjacency_matrix[i][j] == 1){
incidence_matrix[i][counter] = 1;
incidence_matrix[j][counter] = 1;
++counter;
}
}
}
for( int i = 1; i <= numberOfVertices; i++){
for(int j = 1; j <= numberOfEdges; j++){
std::cout<<incidence_matrix[i][j]<<" ";
}
std::cout<<std::endl;
}
The ideas in the code are correct. But the indexing in the array is wrong.
Indexing should start at 0. Note: this also applies when setting up the adjacency matrix.
The numbers you use to name the vertices/nodes where originally 1,2,3,4,5,6. I propose to call them 0,1,2,3,4,5. Your original edge (1,2) then becomes (0,1). But if we consistently rename all the vertices everywhere we end up with the same graph. The advantage of this new naming convention is that we can use these names directly as indices in the C++ data structures you are using. (Provided we use the corresponding integer value and not consider these names to be strings.)
The specification of the Graph becomes
Graph* g = new Graph(numberOfVertices, numberOfEdges);
g->edge[0]->src = 0;
g->edge[0]->dest = 1;
g->edge[1]->src = 0;
g->edge[1]->dest = 4;
g->edge[2]->src = 0;
g->edge[2]->dest = 5;
g->edge[3]->src = 1;
g->edge[3]->dest = 2;
g->edge[4]->src = 1;
g->edge[4]->dest = 4;
g->edge[5]->src = 2;
g->edge[5]->dest = 3;
g->edge[6]->src = 2;
g->edge[6]->dest = 4;
g->edge[7]->src = 3;
g->edge[7]->dest = 4;
g->edge[8]->src = 4;
g->edge[8]->dest = 5;
So printing the adjacency matrix becomes:
std::cout << "Adjacency matrix : " << std::endl;
for (i = 0; i < numberOfVertices; i++)
{
for (j = 0; j < numberOfVertices; j++)
{
std::cout<<adjacency_matrix[i][j]<<" ";
}
std::cout << std::endl;
}
and the calculation of the incidence matrix becomes:
// Incidence Matrix
int counter = 0;
for( int i = 0; i < numberOfVertices; i++){ //numberOfVertices!!
for(int j = i + 1; j < numberOfVertices; j++ ){
if(adjacency_matrix[i][j] == 1){
incidence_matrix[i][counter] = 1;
incidence_matrix[j][counter] = 1;
++counter;
}
}
}
for( int i = 0; i < numberOfVertices; i++){
for(int j = 0; j < numberOfEdges; j++){
std::cout<<incidence_matrix[i][j]<<" ";
}
std::cout<<std::endl;
}
Note that the order of the edges is determined now by the order in which you traverse the adjacency matrix.

C++ display possible bishop moves in an empty chess board

This task asks to display possible bishop moves in a chessboard (8 x 8) as in an example shown below:
x = 4, y = 4
1 0 0 0 0 0 1 0,
0 1 0 0 0 1 0 0,
0 0 1 0 1 0 0 0,
0 0 0 2 0 0 0 0,
0 0 1 0 1 0 0 0,
0 1 0 0 0 1 0 0,
1 0 0 0 0 0 1 0,
0 0 0 0 0 0 0 1
Image for clear understanding
#include <iostream>
using namespace std;
int main() {
int array[8][8], x , y;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
array[i][j] = 0;
}
}
cout << "Input x coordinate: ";
cin >> x;
cout << "Input y coordinate: ";
cin >> y;
for (int i = 0; i < 8; i++)
{ // 1st diagonal
array[x + i][y + i] = 1;
array[x - i][y - i] = 1;
}
for (int i = 0; i < 8; i++)
{ // 2nd diagonal
array[x + i][y - i] = 1;
array[x - i][y + i] = 1;
}
array[x][y] = 2;
for (int i = 0; i < 8; i++) //Cout
{
for (int j = 0; j < 8; j++)
{
cout << array[i][j];
}
cout << endl;
}
return 0;
}
It seems to work only with 1st diagonal
This is more of an algorithm/math answer than C++.
Suppose the grid's bottom left point is the origin (i.e. i = 0, j = 0), and the coordinate of the top right point in the grid is i=7, j=7.
A bishop that is on i=0, j=0 can hit anything on these two lines:
i = j and i = - j
When you put the bishop at point x, y instead of 0,0, these lines change to:
i - x = j - y and i - x = - (j - y)
Now, you can iterate all points in the matrix and check which ones satisfy the line equation:
int main() {
int x, y;
std::cout << "Input x coordinate: ";
std::cin >> x;
std::cout << "Input y coordinate: ";
std::cin >> y;
int array[8][8];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if ((i - x == j - y) || (i - x == -(j - y))) {
array[i][j] = 1;
} else {
array[i][j] = 0;
}
}
}
array[x][y] = 2;
// We should print the matrix from top to bottom.
// j represents the y coordinate, and i represents the x coordinate.
for (int j = 7; j >= 0; j--) {
for (int i = 0; i < 8; i++) {
std::cout << array[i][j];
}
std::cout << std::endl;
}
return 0;
}
It looks like it's working for both diagonals when I run it. There is a small bug that might mess things up though. You'll want to add bounds checks like this:
for (int i = 0; i < 8; i++)
{ // 1st diagonal
if (x + i < 8 && y + i < 8)
array[x + i][y + i] = 1;
if (x - i >= 0 && y - i >= 0)
array[x - i][y - i] = 1;
}
for (int i = 0; i < 8; i++)
{ // 2nd diagonal
if (x + i < 8 && y - i >= 0)
array[x + i][y - i] = 1;
if (x - i >= 0 && y + i < 8)
array[x - i][y + i] = 1;
}
Without these bounds checks you'll be accessing elements outside of the array bounds and could be messing up other entries in the array. There are other ways to do the bounds checking, but this might be the easiest.
To illustrate the issue, assume x = 4 and then in the for loop when i = 5. When you're indexing into the array with array[x - i] that'll be the same as array[-1]. When you index into an array with a negative value you'll be messing with the wrong memory.
I would start with a very simple case.
Suppose we want to plot the diagonal matrix of size 4x4:
i 0 1 2 3
j
0 1 0 0 0
1 0 1 0 0
2 0 0 1 0
3 0 0 0 1
We have a non zero value when:
i = j (I)
Now, suppose we shift this diagonal horizontally so that the non-zero value of the first line is located at X0.
For example, for X0 = 1:
X0
i' 0 1 2 3
j'
0 0 1 0 0
1 0 0 1 0
2 0 0 0 1
3 0 0 0 0
The shifted coordinates are:
i' = i + X0 (II)
Doing the same for shifting vertically by Y0:
j' = j + Y0 (III)
With (II) and (III) in (I) we have:
i' - X0 = j' - Y0 (IV)
Now we do the same for the antidiagonal matrix:
i 0 1 2 3
j
0 0 0 0 1
1 0 0 1 0
2 0 1 0 0
3 1 0 0 0
We have a non zero value when:
j = 3 - i (V)
Shifting horizontally by X0 we have:
i' = -3 + i + X0 (VI)
Shifting vertically by Y0:
j' = j + Y0 (VII)
With (VI) and (VII) in (V):
j' - Y0 = X0 - i' (VIII)
The code just needs to check for (IV) and (VIII):
#include <iostream>
using namespace std;
int main()
{
int array[8][8] = {0,};
int x = 0;
int y = 0;
cout << "Input x coordinate: ";
cin >> x;
cout << "Input y coordinate: ";
cin >> y;
for (int j = 0; j < 8; j++)
for (int i = 0; i < 8; i++)
if ( i - x == j - y
|| j - y == x - i)
array[j][i] = 1;
array[y][x] = 2;
for (int j = 0; j < 8; j++)
{
for (int i = 0; i < 8; i++)
cout << array[j][i];
cout << endl;
}
return 0;
}
Note that the matrix is plotted following the convention array[lines][columns], so to set cartesian coordinates we write array[y][x].

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);
}

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

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;
}

Sudoku solver keeps getting stuck for some reason

So I had to write a program for a computer project for high school and I thought of doing a sudoko solver. The 'solve' algorithm is implemented like this:-
For any points where only one element 'fits' looking at rows, columns, 3x3 set, put that number in. Do this repeatedly till it can't be done anymore. This is seen in the 'singleLeft' function.
If a number 'fits' in some point but nowhere else in the associated row, column or 3x3 set, put that number in. This can be seen in the 'checkOnlyAllowed' function.
If we're not done yet, do a 'guess' - take some number that 'fits' in the point, put it in there and then solve again using this algorithm (recurse) - if it works, we're done.
So far, I have this code:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
//Prints a message and exits the application.
void error(const char msg[])
{
cout << "An error occurred!" << endl;
cout << "Description: " << msg << endl;
exit(0);
}
//A representation of a sudoku board. Can be read from a file or from memory.
class Sudoku
{
protected:
//For a point x, y and a number n in the board, mAllowed[x][y][n]
//is 1 if n is allowed in that point, 0 if not.
int mAllowed[9][9][10];
int filledIn;
public:
/*
* For mBoard[i][j], the location is (i,j) in the below map:
*
* (0,0) (0,1) (0,2) (0,3) (0,4) (0,5) (0,6) (0,7) (0,8)
* (1,0) (1,1) (1,2) (1,3) (1,4) (1,5) (1,6) (1,7) (1,8)
* (2,0) (2,1) (2,2) (2,3) (2,4) (2,5) (2,6) (2,7) (2,8)
*
* (3,0) (3,1) (3,2) (3,3) (3,4) (3,5) (3,6) (3,7) (3,8)
* (4,0) (4,1) (4,2) (4,3) (4,4) (4,5) (4,6) (4,7) (4,8)
* (5,0) (5,1) (5,2) (5,3) (5,4) (5,5) (5,6) (5,7) (5,8)
*
* (6,0) (6,1) (6,2) (6,3) (6,4) (6,5) (6,6) (6,7) (6,8)
* (7,0) (7,1) (7,2) (7,3) (7,4) (7,5) (7,6) (7,7) (7,8)
* (8,0) (8,1) (8,2) (8,3) (8,4) (8,5) (8,6) (8,7) (8,8)
*
*/
int mBoard[9][9];
//Read in from file with given name.
Sudoku(char filename[])
{
filledIn = 0;
int i, j, k;
//Fill the board with 0s.
for (i = 0; i < 9; ++i)
for (j = 0; j < 9; ++j)
mBoard[i][j] = 0;
//Set every number to 'allowed' initially.
for (i = 0; i < 9; ++i)
for (j = 0; j < 9; ++j)
for (k = 1; k <= 9; ++k)
mAllowed[i][j][k] = 1;
//Read in from the file.
ifstream file(filename);
if (!file)
error("File doesn't exist!");
for (i = 0; i < 9; ++i)
for (j = 0; j < 9; ++j)
if (file)
{
int m;
file >> m;
if (m)
set(i, j, m);
}
else
error("Not enough entries in file!");
}
//Solve the board!
int solve()
{
int prevFilledIn;
do
{
prevFilledIn = filledIn;
singleLeft();
checkOnlyAllowed();
} while (filledIn - prevFilledIn > 3);
if (filledIn < 81)
guess();
return filledIn == 81;
}
//Given a point i, j, this looks for places where this point
//disallows a number and sets the 'mAllowed' table accordingly.
void fixAllowed(int i, int j)
{
int n = mBoard[i][j], k;
for (k = 0; k < 9; ++k)
mAllowed[i][k][n] = 0;
for (k = 0; k < 9; ++k)
mAllowed[k][j][n] = 0;
//Look in 3x3 sets too. First, set each coordinate to the
//highest multiple of 3 below itself. This takes us to the
//top-left corner of the 3x3 set this point was in. Then,
//add vectorially all points (x,y) where x and y each are
//one of 0, 1 or 2 to visit each point in this set.
int x = (i / 3) * 3;
int y = (j / 3) * 3;
for (k = 0; k < 3; ++k)
for (int l = 0; l < 3; ++l)
mAllowed[x + k][y + l][n] = 0;
mAllowed[i][j][n] = 1;
}
//Sets a point i, j to n.
void set(int i, int j, int n)
{
mBoard[i][j] = n;
fixAllowed(i, j);
++filledIn;
}
//Try using 'single' on a point, ie, only one number can fit in this
//point, so put it in and return 1. If more than one number can fit,
//return 0.
int trySinglePoint(int i, int j)
{
int c = 0, m;
for (m = 1; m <= 9; ++m)
c += mAllowed[i][j][m];
if (c == 1)
{
for (m = 1; m <= 9; ++m)
if (mAllowed[i][j][m])
set(i, j, m);
//printBoard();
return 1;
}
return 0;
}
//Try to solve by checking for spots that have only one number remaining.
void singleLeft()
{
for (;;)
{
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j)
if (!mBoard[i][j])
if (trySinglePoint(i, j))
goto logic_worked;
//If we reached here, board is either full or unsolvable by this logic, so
//our job is done.
return;
logic_worked:
continue;
}
}
//Within rows, columns or sets, whether this number is 'allowed' in spots
//other than i, j.
int onlyInRow(int n, int i, int j)
{
for (int k = 0; k < 9; ++k)
if (k != j && mAllowed[i][k][n])
return 0;
return 1;
}
int onlyInColumn(int n, int i, int j)
{
for (int k = 0; k < 9; ++k)
if (k != i && mAllowed[k][j][n])
return 0;
return 1;
}
int onlyInSet(int n, int i, int j)
{
int x = (i / 3) * 3;
int y = (j / 3) * 3;
for (int k = 0; k < 3; ++k)
for (int l = 0; l < 3; ++l)
if (!(x + k == i && y + l == j) && mAllowed[x + k][y + l][n])
return 0;
return 1;
}
//If a number is 'allowed' in only one spot within a row, column or set, it's
//guaranteed to have to be there.
void checkOnlyAllowed()
{
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j)
if (!mBoard[i][j])
for (int m = 1; m <= 9; ++m)
if (mAllowed[i][j][m])
if (onlyInRow(m, i, j) || onlyInColumn(m, i, j) || onlyInSet(m, i, j))
set(i, j, m);
}
//Copy from a given board.
void copyBoard(int board[9][9])
{
filledIn = 0;
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j)
{
if (board[i][j] > 0)
++filledIn;
mBoard[i][j] = board[i][j];
}
}
//Try to solve by 'guessing'.
void guess()
{
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j)
for (int n = 1; n <= 9; ++n)
if (!mBoard[i][j])
if (mAllowed[i][j][n] == 1)
{
//Do a direct copy so that it gets the 'mAllowed'
//table too.
Sudoku s = *this;
//Try solving with this number at this spot.
s.set(i, j, n);
if (s.solve())
{
//It was able to do it! Copy and report success!
copyBoard(s.mBoard);
return;
}
}
}
//Print the board (for debug purposes)
void printBoard()
{
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
cout << mBoard[i][j] << " ";
cout << endl;
}
cout << endl;
char s[5];
cin >> s;
}
};
int main(int argc, char **argv)
{
//char filename[42];
//cout << "Enter filename: ";
//cin >> filename;
char *filename = argv[1];
Sudoku s(filename);
if (!s.solve())
error("Couldn't solve!");
cout << "Solved! Here's the solution:" << endl << endl;
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
cout << s.mBoard[i][j] << " ";
cout << endl;
}
return 0;
}
(code including line numbers: http://sprunge.us/AiUc?cpp)
Now I understand that it isn't very good style, but it came out of a late-night coding session and also we use an older compiler in the school lab so I had to do some things differently (in that compiler, the standard headers have the '.h' extension, variables declared in for loops are in outside-for scope, ... ).
The file should contain whitespace-delimited digits for each spot in the board starting from the top-left going left to right and top to bottom, with empty spots signified by '0's.
For the following file, it works rather well:
5 3 0 0 7 0 0 0 0
6 0 0 1 9 5 0 0 0
0 9 8 0 0 0 0 6 0
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9
However, this one gives it trouble:
0 9 4 0 0 0 1 3 0
0 0 0 0 0 0 0 0 0
0 0 0 0 7 6 0 0 2
0 8 0 0 1 0 0 0 0
0 3 2 0 0 0 0 0 0
0 0 0 2 0 0 0 6 0
0 0 0 0 5 0 4 0 0
0 0 0 0 0 8 0 0 7
0 0 6 3 0 4 0 0 8
If I comment out the print statements and track the progress I can see that it starts by heading out in the wrong direction at points. Eventually it gets stuck toward the end and the backtracking never gets far back enough. I think it's something wrong with the 'checkOnlyAllowed' part...
What do you think could be the problem?
Also - I know I could've used a bitfield for the 'mAllowed' table but we don't officially know about bitwise operations yet in school. :P
At line 170 you have a goto that is jumping out of a for loop, then continuing. This could give you some weird behavior with continuing the wrong loop, behavior that might depend on the specific compiler.
Try replacing lines 164-177 with:
164 for (;;)
165 {
166 bool successfullyContributedToTheBoard = false;
167 for (int i = 0; i < 9; ++i)
168 for (int j = 0; j < 9; ++j)
169 if (!mBoard[i][j])
170 if (trySinglePoint(i, j))
171 successfullyContributedToTheBoard = true;
172 if (!successfullyContributedToTheBoard)
173 return;
174 }
I didn't look at your code but your strategy is exactly the same as the one I used to code a Sudoku solver. But I can't remember it being very slow. I got solutions in an instant. The maximum number of "guesses" the program had do make was 3 during my tests. That was for Sudoku problems which were supposed to be very hard. Three is not a big number with respect to back tracking and you can pick a cell which has only a few possibilities left (two or three) which limits the search space to about 20-30 states only (for hard Sudoku problems).
What I'm saying is, it's possible to use this strategy and solve Sudoku problems really fast. You only have to figure out how to optimize your code. Try to avoid redundant work. Try to remember things so you don't need to recalculate them again and again.
Alright, I got it working! It seems that the i, j loop within 'guess' was unecessary - ie., it should only do a guess on one empty spot because its 'child processes' will handle the rest. Fixing this actually made the code simpler. Now it works really well, and actually its very quick!
Thanks for your help, everyone. ;-)