bfs,只过了两个,大佬救命
查看原帖
bfs,只过了两个,大佬救命
947842
aton_puck楼主2023/7/8 22:20
#include <iostream>
#include <queue>
using namespace std;
const int N=2010;
char D[N][N];
int m,n;
int bfs(int row,int col)
{
    D[row][col] = '0';
    queue<pair<int,int>> q;
    q.push({row,col});
    int dx[4] = {0,0,-1,1};
    int dy[4] = {-1,1,0,0};

    while(!q.empty())
    {
        int a = q.front().first;
        int b = q.front().second;
        q.pop();
        for(int i=0 ; i<4 ; i++)
        {
            int rw = a + dx[i];
            int cl = b + dy[i];
            if(rw>=0&&rw<n && cl>=0&&cl<m && (D[rw][cl]=='.' || D[rw][cl]=='d'))
            {
                if(D[rw][cl] == 'd') {return D[a][b] - '0' + 1;}
                D[rw][cl] = D[a][b] + 1;
                q.push({rw,cl});
            }
        }
    }
    return -1;
}

int main()
{
    cin>>n>>m;
    cin.ignore();
    for(int i=0 ; i<n ; i++)
        cin.getline(D[i],N);  //the second paramenter should be N,just the size of D[i]
    int row,col; //flag the location of "m"
    for(int i=0 ; i<n ; i++)
        for(int j=0 ; j<m ; j++)
            if(D[i][j] == 'm') 
            {
                row=i;
                col=j;
            }
    int result = bfs(row,col);
    if(result != -1) cout<<result<<endl;
    else cout<<"No Way!"<<endl;
    return 0;
}
2023/7/8 22:20
加载中...