一、题目大意
按列排序找出所有八皇后解
二、解题思路
定义dfs(i)
为放置第i
列的行为,深搜
三、代码
/**
以列为基准搜索
**/
#include<iostream>
using namespace std;
const int MAX = 104;
const int N = 8;
int grad[10][10];
int dir[8][2] = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,-1},{-1,1}};
int cnt;
int ans[MAX];
int out_of_edge(int x, int y)
{
if(x < 0 || x >= 8 || y < 0 || y >= 8)
return 1;
return 0;
}
int ok(int r, int c)
{
for(int i=0; i<8; i++)
{
int nx, ny;
nx = r + dir[i][0];
ny = c + dir[i][1];
while(!out_of_edge(nx, ny))
{
if(grad[nx][ny])
return 0;
nx = nx + dir[i][0];
ny = ny + dir[i][1];
}
}
return 1;
}
void dfs(int c)
{
if(c == N)
{
for(int j=0; j<N; j++)
{
for(int i=0; i<N; i++)
{
if(grad[i][j])
{
ans[cnt] = ans[cnt] * 10 + i+1;
break;
}
}
}
cnt++;
}
for(int r=0; r<N; r++)
{
if(ok(r, c))
{
grad[r][c] = 1;
dfs(c+1);
grad[r][c] = 0;
}
}
}
int main()
{
cnt = 0;
dfs(0);
int T;
cin >> T;
int n;
while(T--)
{
cin >> n;
cout << ans[n-1] << endl;
}
return 0;
}