<pre>
#include <vector>
using namespace std;
// Defines
#define MAX_K 8
void solveboard(const std::vector<short int> &board, std::vector<std::vector<short int> > &solution)
{
int column[MAX_K] = {0, 0, 0, 0, 0, 0, 0, 0};
int row[MAX_K] = {0, 0, 0, 0, 0, 0, 0, 0};
int up_diagonal[2 * MAX_K - 1] = {0, 0, 0, 0, 0, 0, 0, 0};
int down_diagonal[2 * MAX_K - 1] = {0, 0, 0, 0, 0, 0, 0, 0};
int row_exists[MAX_K] = {0, 0, 0, 0, 0, 0, 0, 0};
int x, y, i;
if (board.size() == MAX_K)
{
solution.resize(1);
solution[0].resize(MAX_K);
for (y = 0; y < MAX_K; y++)
solution[0][y] = board[y];
return;
}
for (i = board.size() - 1; i >= 0; i--)
{
y = board[i];
x = y >> 3;
y = y & 7;
if (column[x] || row_exists[y] || up_diagonal[y + x] || down_diagonal[y + MAX_K - x - 1])
return;
row[y] = x; // only need one place to keep track
down_diagonal[y + MAX_K - x - 1] = 1;
up_diagonal[y + x] = 1;
column[x] = 1;
row_exists[y] = 1;
}
x = 0;
// skip all rows filled in before this function was called
for (y = 0; y < MAX_K && row_exists[y]; y++);
while (true)
{
if (x == MAX_K)
{
// skip all rows filled in before this function was called
for (y--; y >= 0 && row_exists[y]; y--);
if (y < 0)
break;
// go down a row
x = row[y];
down_diagonal[y + MAX_K - x - 1] = 0;
up_diagonal[y + x] = 0;
column[x] = 0;
}
else if (!(column[x] || up_diagonal[y + x] || down_diagonal[y + MAX_K - x - 1]))
{
row[y] = x;
if (y + 1 != MAX_K)
{
// go up a row
down_diagonal[y + MAX_K - x - 1] = 1;
up_diagonal[y + x] = 1;
column[x] = 1;
// skip all rows filled in before this function was called
for (y++; y < MAX_K && row_exists[y]; y++);
if (y < MAX_K)
{
x = 0;
continue;
}
}
// found a solution
i = solution.size();
solution.resize(i + 1);
solution[i].resize(MAX_K);
for (y = 0; y < MAX_K; y++)
solution[i][y] = y | (row[y] << 3);
y = MAX_K - 1;
// make it so the row will pop in the next loop
x = MAX_K;
continue;
}
x++;
}
}
</pre>
