bfs求调

B3625 迷宫寻路

Lemon_zqp @ 2024-01-15 13:04:04

#include<bits/stdc++.h>
using namespace std;

bool mp[105][105];
int n, m;
int dx[5] = {-1, 1, 0, 0};
int dy[5] = {0, 0, -1, 1};

struct node{
    int x, y;
};

queue<node> q;

void bfs(int x, int y){
    mp[x][y] = false;
    q.push({x, y});
    while(!q.empty()){
        node w = q.front();
        q.pop();
        if(w.x == n && w.y == m){
            cout << "Yes";
            exit(0);
        }
        for(int i = 0; i < 4; i++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && mp[nx][ny]){
                q.push({nx, ny});
                mp[nx][ny] = false;
            }
        }
    }

}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++){
            char a;
            cin >> a;
            if(a == '.'){
                mp[i][j] = true;
            }
            else{
                mp[i][j] = false;
            }
        }
    }
    bfs(1, 1);
    cout << "No";
    return 0;
}

by 名字好难取144 @ 2024-01-15 14:33:03

@Lemon_zqp 错误代码在 26 行

int nx = x + dx[i];
int ny = y + dy[i];

应该改为

int nx = w.x + dx[i];
int ny = w.y + dy[i];

by H2ptimize @ 2024-01-15 14:35:03

@Lemon_zqp 26 27 行,没加 w.


|