1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include <iostream>
#include <iomanip>
using namespace std;
const int M = 4, N = 5;
const bool showSolutions = false;
int grid[M][N];
int solutions = 0;
void place (int depth)
{
if (2*(depth-1) == M*N)
{
if (showSolutions)
{
for (int x = 0; x < M; ++x)
{
for (int y = 0; y < N; ++y)
cout << setw(3) << grid[x][y];
cout << "\n";
}
cout << "\n";
}
++solutions;
}
else
for (int x = 0; x < M; ++x)
for (int y = 0; y < N; ++y)
if (grid[x][y] == 0)
{
grid[x][y] = depth;
if (x+1 < M && grid[x+1][y] == 0)
{
grid[x+1][y] = depth;
place(depth+1);
grid[x+1][y] = 0;
}
if (y+1 < N && grid[x][y+1] == 0)
{
grid[x][y+1] = depth;
place(depth+1);
grid[x][y+1] = 0;
}
grid[x][y] = 0;
return;
}
}
int main(int argc, const char * argv[])
{
place(1);
std::cout << solutions << " solutions\n";
return 0;
} |
Partager