思路:
bfs
判断0和1然后模拟
最后统计一下步数就好了
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int dx[5] = {
0, 0, 0, 1, -1};
const int dy[5] = {
0, 1, -1, 0, 0};
int a[1005][1005], pd[1005][1005];
int dis[1005][1005];
int n, l, r;
bool check(int x, int y)
{
if(x > n || y > n || x < 1 || y < 1)return 0;
if(a[x][y] || pd[x][y])return 0;
return 1;
}
void BFS(int a, int b)//搜索
{
memset(pd, false, sizeof(pd));
memset(dis, 0, sizeof(dis));
queue<int>hx, hy;
hx.push(a), hy.push(b);
pd[a][b] = 1, dis[a][b] = 0;
while(hx.size())
{
int xx = hx.front(); hx.pop();
int yy = hy.front(); hy.pop();
int x = xx + dx[1], y = yy + dy[1];
for(int i = 1; i <= 4; i++)
if(check(xx + dx[i], yy + dy[i]))
{
x = xx + dx[i], y = yy + dy[i];
dis[x][y] = dis[xx][yy] + 1;
pd[x][y] = 1;
hx.push(x), hy.push(y);
if(x == l && y == r)
{
printf("%d", dis[x][y]);
return;
}
}
}
return;
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
{
char c;
cin >> c;
a[i][j] = c - '0';//转换
}
int x, y;
scanf("%d%d%d%d", &x, &y, &l, &r);
BFS(x, y);
return 0;
}