再来走个迷宫!
答案:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N=110;
int n,m,a,b,x,y;
int g[N][N];
int dist[N][N];
typedef pair<int,int> PII;
queue<PII> q;
int n1,m1;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
//上右下左
int bfs(int x1,int y1,int x,int y)
{
memset(dist,-1,sizeof dist);
q.push({x1,y1});
dist[x1][y1]=0;//要把羊驼的起始点作为0步点
while(!q.empty())
{
PII t=q.front();
q.pop();
for(int i=0;i<4;i++)
{
n1=t.first+dx[i];
m1=t.second+dy[i];
if(n1<1||n1>n||m1<1||m1>m) continue;
if(g[n1][m1]!=0) continue;
if(dist[n1][m1]>0) continue;//>0就表示已经走过了,不能再走一遍
q.push({n1,m1});
dist[n1][m1]=dist[t.first][t.second]+1;
if(n1==x&&m1==y) return dist[x][y];
}
}
return dist[x][y];
}
int main()
{
scanf("%d %d",&n,&m);
scanf("%d %d %d %d",&a,&b,&x,&y);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>g[i][j];
}
}
int res;
res=bfs(a,b,x,y);
cout<<res;
return 0;
}
/*输入数据:
5 5
2 1 4 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0 */
但第三个数据输出错误了,不知道为什么