题目大意
解题思路
- 按排作为深度进行
DFS
,对每一排,以放在哪一列
作为分支扩展。 - 注意输出问题, 可能官方是按列作为深度的。
代码
#include<iostream>
using namespace std;
int nx, ny;
int grad[8][8];
int num;
void print_grad()
{
cout << "No. " << num++<< endl;
for(int j=0; j<8; j++)
{
for(int i=0; i<8; i++)
{
if(i)
cout << " " << grad[i][j];
else
cout << grad[i][j];
}
cout << endl;
}
}
bool out_edge(int x, int y)
{
if(x < 0 || x >= 8 || y < 0 || y >= 8)
return true;
return false;
}
bool is_ok(int row, int clo)
{
for(int i=0; i<8; i++)
{
if(grad[i][clo])
return false;
if(grad[row][i])
return false;
}
int tmpx = row;
int tmpy = clo;
while(!out_edge(tmpx, tmpy))
{
if(grad[tmpx][tmpy])
return false;
tmpx--;
tmpy--;
}
tmpx = row;
tmpy = clo;
while(!out_edge(tmpx, tmpy))
{
if(grad[tmpx][tmpy])
return false;
tmpx++;
tmpy++;
}
tmpx = row;
tmpy = clo;
while(!out_edge(tmpx, tmpy))
{
if(grad[tmpx][tmpy])
return false;
tmpx--;
tmpy++;
}
tmpx = row;
tmpy = clo;
while(!out_edge(tmpx, tmpy))
{
if(grad[tmpx][tmpy])
return false;
tmpx++;
tmpy--;
}
return true;
}
void dfs(int row)
{
if(row == 8)
{
print_grad();
return;
}
for(int i=0; i<8; i++)
{
if(is_ok(row, i))
{
grad[row][i] = 1;
dfs(row+1);
grad[row][i] = 0;
}
}
}
int main()
{
num = 1;
dfs(0); // 确定第几排
return 0;
}