求助bfs解法

B3625 迷宫寻路

JSJ_WuYeHao @ 2024-12-14 15:55:18

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

typedef pair<int, int> PII;

const int N = 110;

int n, m;
char g[N][N];
int d[N][N];

bool bfs()
{
    queue<PII> a;
    memset(d, -1, sizeof(d));
    d[0][0] = 0;
    a.push({ 0,0 });
    int dx[4] = { 0,0,1,-1 }, dy[4]={ 1,-1,0,0 };
    while (a.size())
    {
        auto t = a.front();
        a.pop();
        for (int i = 0; i < 4; i++)
        {
            int x = t.first + dx[i], y = t.second + dy[i];
            if (x >= 0 && y >= 0 && x < n  && y < m  && g[x][y] == '.' && d[x][y] == -1)
            {
                d[x][y] = d[t.first][t.second] + 1;
                a.push({ x,y });
            }
        }
    }
    if (d[n - 1][m - 1] == -1)return false;
    return true;
}

int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> g[i][j];

    if (bfs())cout << "Yes";
    else cout << "No";
    return 0;
}

为什么我的全错了


by A_cz @ 2024-12-21 17:34:50

#include<iostream> 
using namespace std; 
int fx[5]={0,0,1,0,-1},fy[5]={0,1,0,-1,0};
char a[200][200]; 
int q[40000][5],head=1,tail=1,tx,ty,n,m; 
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)cin>>a[i][j];
    q[1][1]=1,q[1][2]=1,a[1][1]='#';
    while(head<=tail){
        for(int i=1;i<=4;i++){
            tx=q[head][1]+fx[i],ty=q[head][2]+fy[i];
            if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&a[tx][ty]!='#'){
                a[tx][ty]='#';
                tail++;
                q[tail][1]=tx;
                q[tail][2]=ty;
                if(tx==n&&ty==m){ 
                    cout<<"Yes";
                    return 0;
                }
            }
        }
        head++;
    }
    cout<<"No";
    return 0;
}

|