第一个的代码:
#include<iostream>
#include<vector> using namespace std; bool isLegal(int i, int j, vector<string> ¤t)
{
int size = current.size();
int x = i-, y = j;
while (x >= )
{
if (current[x][y] == 'Q')
return false;
x--;
}
x = i-;
y = j - ;
while (x >= && y >= )
{
if (current[x][y] == 'Q')
return false;
x--;
y--;
}
x = i - ;
y = j + ;
while (x >= && y < size)
{
if (current[x][y] == 'Q')
return false;
x--;
y++;
}
return true;
} void getResult(int row, int index, vector<vector<string>> &result, vector<string> ¤t, int size)
{
if (row == size)
result.push_back(current);
else
{
while (index < size)
{
current[row][index] = 'Q';
if (isLegal(row, index, current))
getResult(row + , , result, current, size);
current[row][index] = '.';
index++;
}
}
} vector<vector<string>> solveNQueens(int n)
{
vector<vector<string>> result;
string s = "";
for (int i = ; i < n; i++)
s.push_back('.');
vector<string> current(n, s);
getResult(, , result, current, n);
return result;
} int main()
{
vector<vector<string>> result = solveNQueens();
for (int i = ; i < result.size(); i++)
{
for (int j = ; j < result[i].size(); j++)
cout << result[i][j].c_str() << endl;
cout << "-_________________________________________-" << endl;
}
return ;
}
第二个的代码:
得,忘了保存了,算了,不贴了,这题也就做到这份上了,讨论区里那个用位的我真是佩服死你啦。。。。。!!!!!!!!!