离开超市
2025-01-24 11:18:08
发布于:上海
#include<bits/stdc++.h>
using namespace std;
int n,m;char g[1005][1005];
int dist[1005][1005];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
int x;int y;
};
int main()
{
cin >> n ;
m = n;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++)
{
cin >> g[i][j];
}
}
queue<node> q;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++)
{
dist[i][j] = 0x3f3f3f3f;
}
}
int x1,y1;cin >> x1 >> y1;
dist[x1][y1] = 0;
q.push({x1,y1});
while(q.size())
{
node top = q.front();
q.pop();
for(int i = 0;i < 4;i++)
{
int nx = top.x + dir[i][0];
int ny = top.y + dir[i][1];
if(nx < 1 || ny < 1 || nx > n|| ny > m || g[nx][ny] == '1')
continue;
if(dist[nx][ny] > dist[top.x][top.y]+1)
{
dist[nx][ny] = dist[top.x][top.y]+1;
q.push({nx,ny});
}
}
}
int x2,y2;cin >> x2 >> y2;
if(dist[x2][y2] == 0x3f3f3f3f) cout << "-1";
else cout << dist[x2][y2];
}
这里空空如也
有帮助,赞一个