题目为解救小哈
第一种为dfs
#include <iostream>
using namespace std;
int dx,dy,n,m,imin=99999999;
int a[1000][1000],book[1000][1000];
void dfs(int x,int y,int step)
{
int next[4][2]=
{
{0,1},
{1,0},
{0,-1},
{-1,0}
};
int tx,ty;
if(x==dx&&y==dy)
{
if(step<imin) imin=step;
return ;
}
for(int k=0;k<4;k++)//枚举4个方向
{
tx=x+next[k][0];
ty=y+next[k][1];
if(tx<1||tx>n||ty<1||ty>m)
continue;
if(a[tx][ty]==0&&book[tx][ty]==0)
{
book[tx][ty]=1;
dfs(tx,ty,step+1);
book[tx][ty]=0;
}
}
return ;
}
int main()
{
int sx,sy;
cin >> n >> m;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
cin >> a[i][j];
cin >> sx >> sy >> dx >> dy;
book[sx][sy]=1;//从当前位置开始搜索
dfs(sx,sy,0);
cout << imin;
return 0;
}
第二种为bfs
#include <iostream>
#include <queue>
using namespace std;
int sx,sy,dx,dy,n,m,imin=99999999;
int a[100][100],book[100][100];
struct node
{
int x,y,s;
//x,y存坐标,s存步数
};
void bfs(int x,int y)
{
int next[4][2]={
{0,1},
{1,0},
{0,-1},
{-1,0}
};//上下左右移动
queue<node> p;
node head,tail;//一个头一个尾
head.x=x;
head.y=y;
head.s=0;//这三行是存个头
p.push(head);//头塞进队列
while(!p.empty())//检查是否为空
{
head=p.front(); //将第一个元素变成头
p.pop();//删去第一个检查过的元素便于往后查找
if(head.x==dx&&head.y==dy)//查找到直接退出,bfs一定是最优解
{
imin=head.s;
return;
}
for(int k=0;k<4;k++)//枚举四个方向
{
tail.x=head.x+next[k][0];
tail.y=head.y+next[k][1];
if(tail.x<1||tail.x>n||tail.y<1|tail.y>m) continue;//判断越界
if(a[tail.x][tail.y]==0&&book[tail.x][tail.y]==0)
{
book[tail.x][tail.y]=1; //标记
tail.s=head.s+1; //下一次步数=这次+1
p.push(tail);//这次的尾变成下一次的头
}
}
}
}
int main()
{
cin >> n >> m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin >> a[i][j];
cin >> sx >> sy >> dx >> dy;
book[sx][sy]=1;//将开始位置标记
bfs(sx,sy);
cout << imin ;
}