1101. 献给阿尔吉侬的花束

旧城冷巷雨未停 提交于 2020-02-28 20:29:51

题目链接:

https://www.acwing.com/problem/content/1103/

 

题解:

!!!

要么在bfs内部定义queue,要么每次在进入bfs时将queue清空!
!!!

 

AC代码:#include <cstdio>

#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#define x first
#define y second
using namespace std;

typedef pair<int ,int> PII;

int T;
int r, c;
const int N = 205;
char g[N][N];
int st[N][N];


int bfs(PII start,PII end){
    //坑!
    queue<PII> q;
    q.push(start);
    st[start.x][start.y] = 0;
    int dx[4] = {-1,1,0,0};
    int dy[4] = {0,0,-1,1};
    while(!q.empty()){
        PII now = q.front();
        q.pop();
        // (-1,0) (1,0) (0,-1) (0,1)
        for(int i=0;i<4;i++){
            int nx = now.x+dx[i];
            int ny = now.y+dy[i];
            if(nx < 0 || nx >= r || ny < 0 || ny >= c) continue;
            if(st[nx][ny] != -1) continue;
            if(g[nx][ny] == 'E'){
                return st[now.x][now.y]+1;
            }
            if(g[nx][ny] == '#') continue;
            q.push(make_pair(nx,ny));
            st[nx][ny] = st[now.x][now.y]+1;
        }
    }
    
    return -1;
}

int main(){
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&r,&c);
        for(int i=0;i<r;i++) scanf("%s",g[i]);
        PII s,e;
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++){
                if(g[i][j] == 'S'){
                    s = make_pair(i,j);
                }
                if(g[i][j] == 'E'){
                    e = make_pair(i,j);
                }
            }
            
        // fill(st,st+N*N,-1);
        memset(st,-1, sizeof(st));
        int res = bfs(s,e);
        if(res == -1) printf("oop!\n");
        else printf("%d\n",res);
    }
    return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!