74 lines
1.4 KiB
C++
74 lines
1.4 KiB
C++
#include<bits/stdc++.h>
|
|
using namespace std;
|
|
|
|
struct node {
|
|
int x, y, s;
|
|
};
|
|
|
|
queue<node> q;
|
|
int a[51][51];
|
|
int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; // 方向数组
|
|
bool flag = false, book[51][51];
|
|
int n, m, sx, sy, ex, ey;
|
|
|
|
void bfs(int sx,int sy)
|
|
{
|
|
q.push({sx, sy, 0}); // 星星之火, 可以燎原
|
|
book[sx][sy] = true;
|
|
|
|
while(!q.empty() && !flag) {
|
|
node temp = q.front();
|
|
q.pop();
|
|
for(int i=0; i<4;i++) {
|
|
//算出新的位置坐标
|
|
int nx = temp.x + dir[i][0];
|
|
int ny = temp.y + dir[i][1];
|
|
//判断新的位置是否越界
|
|
if(nx<1 || nx > n || ny < 1 || ny > m)
|
|
continue;
|
|
// 如果新的位置是平地 并且 没有走过
|
|
if(a[nx][ny]==0 && !book[nx][ny]) {
|
|
q.push({nx, ny, temp.s+1});
|
|
book[nx][ny] = true;
|
|
// 新的位置是否为终点
|
|
if(nx==ex && ny==ey) {
|
|
flag = true;
|
|
cout<<temp.s+1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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>>ex>>ey;
|
|
|
|
bfs(sx,sy);
|
|
|
|
if(!flag)
|
|
cout<<"no";
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
5 4
|
|
0 0 1 0
|
|
0 0 0 0
|
|
0 0 1 0
|
|
0 1 0 0
|
|
0 0 0 1
|
|
1 1 4 3
|
|
|
|
输出
|
|
7
|
|
*/
|