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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
#include <iostream>
#include <iomanip>
using namespace std;
char board[8][8];
void clearBoard();
void attempt(int n, int level, int possibility);
void placeQueen(int level, int possibility);
void removeQueen(int level, int possibility);
bool currentPathSuccess(int n, int level, int possibility);
bool currentPathStillViable(int level, int possibility);
void processSuccessfulPath(int n);
int main()
{
int n;
clearBoard();
cout << "Permutation of integers from 1 to ? ";
cin >> n;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++)
{
attempt(n, i, j);
}
}
system("pause");
return 0;
}
void clearBoard()
{
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
board[i][j] = '_';
}
void attempt(int n, int level, int possibility)
{
placeQueen(level, possibility);
if (currentPathSuccess(n, level, possibility))
{
processSuccessfulPath(n);
}
else if (currentPathStillViable(level, possibility))
for (int i = 0; i <= n; i++)
attempt(n, level + 1, possibility + 1);
removeQueen(level, possibility);
}
void placeQueen(int level, int possibility)
{
board[level][possibility] = 'Q';
}
void removeQueen(int level, int possibility)
{
board[level][possibility] = '_';
}
bool currentPathSuccess(int n, int level, int possibility)
{
bool success = true;
int i = 0;
int j = 0;
if (n > level)
success = false;
else
{
while ((i <= level - 1) && success)
{
success = board[i][j] != board[level][possibility];
i++;
}
}
return success;
}
bool currentPathStillViable(int level, int possibility)
{
bool viable = true;
int i = 0;
int j = 0;
while ((i <= level - 1) && viable)
{
viable = board[i][j] /*!= board[level][possibility]*/;
i++;
}
return viable;
}
void processSuccessfulPath(int n)
{
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= n; j++)
{
cout << setw(3) << board[i][j];
}
cout << endl;
}
cout << endl;
}
|