前言
类似八皇后的一道题目,可以用DFS
题目详情
解题代码
#include<iostream>
using namespace std;
const int N = 10;
int a,b,c,d;
int x[8]={1,1,2,2,-1,-1,-2,-2};
int y[8]={2,-2,1,-1,2,-2,1,-1};
bool g[N][N];
int ans=-1;
void dfs(int aa,int bb,int step)
{
if(ans != -1 && step > ans) return; //剪枝:求的是最小步骤
else if(aa==c && bb ==d) //当满足条件返回
{
ans =step;
return;
}
else
{
for(int i=0;i<8;i++) //遍历每一个可以走的方向
{
int xx=aa+x[i],yy=bb+y[i];
if(xx >0 && xx <=8 && yy >0 && yy <=8 && !g[xx][yy])
//判断是否越界
{
g[xx][yy]=true;
dfs(xx,yy,step+1);
g[xx][yy]=false;
}
}
}
}
int main()
{
cin >> a >> b >> c >> d;
g[a][b]=true;
dfs(a,b,0);
cout << ans;
return 0;
}