1.26-寒假集训-2【广度优先搜索】

· · 个人记录

广度优先搜索(BFS)

-T725354 仙岛求药-

思路

由于copy第一题判断合法点的条件忘记转int而痛失100pts的屑

Code

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e3+10;
struct node
{
    int x,y;
}ans[N][N];
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
int n,m,sx,sy,ex,ey,a[N][N];
bool vis[N][N];
bool check(int x,int y)
{
    return (x>=1 && x<=n && y>=1 && y<=m && vis[x][y]==false && a[x][y]!=1);
}
void out(int x,int y)
{
    if(ans[x][y].x==-1 && ans[x][y].y==-1)
    {
        cout<<"("<<x<<","<<y<<")";
        return ;
    }
    out(ans[x][y].x,ans[x][y].y);
    cout<<"->("<<x<<","<<y<<")";
}
void bfs()
{
    queue<node> q;
    q.push({sx,sy});
    vis[sx][sy]=true;
    ans[sx][sy]={-1,-1};
    while(!q.empty())
    {
        node f=q.front();
        q.pop();
        if(f.x==ex && f.y==ey)
        {
            out(ex,ey);
            return ;
        }
        for(int i=0;i<4;i++)
        {
            int x=f.x+dx[i];
            int y=f.y+dy[i];
            if(check(x,y))
            {
                vis[x][y]=true;
                ans[x][y]={f.x,f.y};
                q.push({x,y});
            }
        }
    }
    cout<<"no way";
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    memset(vis,false,sizeof(vis));
    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();
    return 0;
}

-P2960 [USACO09OCT] Invasion of the Milkweed G-

思路