救援

大概是我第一道没看题解写出来的 bfs 。

又写了 30min ,尽管题确实挺简单的。

总结下自己的错误:

注意判断边界和已经走过的路。

不能直接读入,要用字符串,因为矩阵里没有空格。

直接 bfs 即可。

#include<bits/stdc++.h>
using namespace std;
struct node{
    int x,y,s;
};
int n,mp[1001][1001];
int dx[4]={1,0,-1,0},dy[4]={0,-1,0,1};//定义方向 
int a,b,c,d;//起点和终点的坐标 
queue<node>q;
int bfs()
{
    while(!q.empty())
    {
        node p;
        p.x = q.front().x;p.y = q.front().y;p.s = q.front().s;
        q.pop();
        mp[p.x][p.y] = 1;
        if(p.x == c && p.y == d) return p.s;//如果到达就输出答案 
        for(int i = 0;i < 4;i ++)
        {
            node g;
            g.x = p.x+dx[i];g.y = p.y + dy[i];g.s = p.s + 1;
            if(g.x > 0 && g.x <= n && g.y > 0 && g.y <= n && mp[g.x][g.y] == 0) q.push(g);//记得判断是否超出了边界 
        }
    }
    return 0; 
}
int main()
{
    scanf("%d",&n);
    for(int i = 1;i <= n;i ++)
    {
        string cr;
        cin>>cr;
        for(int j=0;j < n;j ++)
        {
            mp[i][j+1] = cr[j] - 48;
        }
    }
    scanf("%d%d%d%d",&a,&b,&c,&d);
    node e;
    e.x = a;e.y = b;e.s = 0; 
    q.push(e);//起点加入队列 
    int ans = bfs();
    cout << ans;
    return 0;
}//完结撒花qwq 
原文地址:https://www.cnblogs.com/ying-xue/p/jiu-yuan.html