[kuangbin带你飞]专题一 简单搜索- J - Fire!

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define INF 0x3f3f3f
int gcd(int a, int b) {return b==0 ? a:gcd(b,a%b);}
const int N = 1010;
int n, m;
int flag;
int jx, jy;
char s[N][N];
int dis[N][N];
int vis[N][N];
int xx[] = {0,0,-1,1};
int yy[] = {-1,1,0,0};

struct node
{
    int x, y, step;
    node(){}
    node(int x, int y, int step):x(x),y(y),step(step){}
};

void bbfs(int fx, int fy)
{
    memset(vis,0,sizeof(vis));
    queue<node>q;
    q.push((node){fx,fy,0});
    vis[fx][fy] = 1;
    dis[fx][fy] = 0;
    while(!q.empty())
    {
        node p = q.front(); q.pop();
        for(int i = 0; i < 4; i++)
        {
            int tx = p.x+xx[i];
            int ty = p.y+yy[i];
            if(tx<1||ty<1||tx>n||ty>m||vis[tx][ty]||s[tx][ty]=='#') continue;
            vis[tx][ty] = 1;
            if(dis[tx][ty]<p.step+1) continue;
            dis[tx][ty] = p.step+1;
            q.push((node){tx,ty,p.step+1});   
        }
    }
}

void bfs()
{
    memset(vis,0,sizeof(vis));
    queue<node>q;
    q.push((node){jx,jy,0});
    vis[jx][jy] = 1;
    while(!q.empty())
    {
        node p = q.front(); q.pop();
        //cout << p.x << " " << p.y << endl;
        if(p.x==1||p.x==n||p.y==1||p.y==m){
            flag = 1;
            printf("%d\n", p.step+1);
            break;
        }
        for(int i = 0; i < 4; i++)
        {
            int tx = p.x+xx[i];
            int ty = p.y+yy[i];
            if(tx<1||ty<1||tx>n||ty>m||vis[tx][ty]) continue;
            if(s[tx][ty]=='#'||p.step+1>=dis[tx][ty]) continue;
            vis[tx][ty] = 1;
            q.push((node){tx,ty,p.step+1});
        }
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d %d", &n, &m);
        for(int i = 1; i <= n; i++) scanf("%s", s[i]+1);
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= m; j++) dis[i][j] = INF;
        }
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= m; j++)
            {
                if(s[i][j]=='F') bbfs(i,j);
                if(s[i][j]=='J'){
                    jx = i; jy = j;
                }
            }
        }
        flag = 0;
        bfs();
        if(!flag) printf("IMPOSSIBLE\n");
    }
    return 0;
}

你可能感兴趣的:(kuangbin)