这道题一开始用的DFS
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
#define Max 666
int m,n,x,y;
bool flag= false;
bool p[Max][Max];
int b[9][3]={{0,0,0},{0,-2,-1},{0,-1,-2},{0,1,-2},{0,2,-1},{0,2,1},{0,1,2},{0,-1,2},{0,-2,1}};
void dfs( int x, int y, int res_x, int res_y, int &res, int count);
int main()
{
cin>>m>>n>>x>>y; //棋盘大小和马的坐标
int res;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
memset(p,true, sizeof(p));
res=Max;
flag=false;
p[x][y]=false; //起点标记为false走过了
dfs(x,y,i,j,res,0);
if(flag)
{
cout<<left<<setw(5)<<res;
}
else
{
cout<<left<<setw(5)<<-1;
}
}
cout<<endl;
}
return 0;
}
void dfs(int x, int y, int res_x, int res_y, int &res, int count)
{
if(x==res_x&&y==res_y)
{
res=min(res,count);
flag=true;
return ;
}
for(int i=1;i<=8;i++)
{
if(x+b[i][1]>=1&&x+b[i][1]<=m&&y+b[i][2]>=1&&y+b[i][2]<=n&&p[x+b[i][1]][y+b[i][2]])
{
p[x+b[i][1]][y+b[i][2]]=false;
dfs(x+b[i][1],y+b[i][2],res_x,res_y,res,count+1);
p[x+b[i][1]][y+b[i][2]]=true;
}
}
}
信心满满的交上去,结果10个点只过了一个点,其他全TL,估计是爆栈了后来我自己试着跑了一下,肉眼可见的效率…果断转了BFS,下面是AC代码
#include <iostream>
#include <cstring>
#include <queue>
#include <iomanip>
using namespace std;
#define Max 666
int m,n,Mi,Mj;
int b[9][3]={{0,0,0},{0,-2,-1},{0,-1,-2},{0,1,-2},{0,2,-1},{0,2,1},{0,1,2},{0,-1,2},{0,-2,1}};
bool flag[Max][Max];
int a[Max][Max];
bool judge(int x,int y,int m,int n);
void BFS(int Mi,int Mj);
struct Node
{
int x,y,step;
};
int main()
{
cin>>m>>n>>Mi>>Mj; //棋盘大小和马的坐标
int res;
memset(flag, false, sizeof(flag)); //假设所有的节点都没有入队
BFS(Mi,Mj);
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(!flag[i][j])
{
cout<<left<<setw(5)<<-1;
} else
{
cout<<left<<setw(5)<<a[i][j];
}
}
cout<<endl;
}
return 0;
}
void BFS(int Mi,int Mj)
{
Node node;
node.x=Mi;
node.y=Mj;
node.step=0;
a[Mi][Mj]=0;
flag[Mi][Mj]=true;
queue<Node> queue;
queue.push(node);
while(!queue.empty())
{
Node temp=queue.front();
queue.pop();
for(int i=1;i<=8;i++)
{
int xi=temp.x+b[i][1];
int yi=temp.y+b[i][2];
if(judge(xi,yi,m,n))
{
node.x=xi;
node.y=yi;
node.step=temp.step+1;
queue.push(node);
flag[xi][yi]=true;
a[xi][yi]=temp.step+1;
}
}
}
}
bool judge(int x,int y,int m,int n)
{
if(x>=1&&x<=m&&y>=1&&y<=n&& !flag[x][y])
{
return true;
} else
{
return false;
}
}
最短路径还是得看BFS,寻找层数,找到时候的层数就是最短的步数