汤圆の拯救计划

来源:互联网 发布:javascript好不好 编辑:程序博客网 时间:2024/04/28 14:36
QAQ蒟蒻每一次都可以移动到相邻的非墙的格子中,每次移动都要花费1个单位的时间

有公共边的格子定义为相邻

Input

一开始为一个整数T代表一共有T组数据

每组测试数据的第一行有两个整数n,m (2<=n,m<=300)

接下来的n行m列为大魔王的迷宫,其中

’#’为墙壁,‘_‘为地面

A代表QAQ蒟蒻,O代表汤圆公主:

Output

一组数据输出一个整数代表从QAQ蒟蒻到汤圆的位置的最短时间

如果QAQ蒟蒻不能到达汤圆的位置,输出-1

Example Input

23 3__A_##__O2 2A##O

Example Output

6-1


很典型的搜索题,结果比赛的时候我居然写了DFS(汗...  所以一直超时,用BFS,得到的一定是最短的

#include <iostream>#include <cstdio>#include <queue>using namespace std;const int N = 310;typedef struct node{    int u, v, step;     //u,v为坐标,step为步数}Node;char str[N][N];bool map[N][N];int n, m;int xx[4] = {1,0,0,-1}, yy[4] = {0,1,-1,0};int BFS(int s, int e){    map[s][e] = 1;    Node t, x;    queue<Node> q;    t.u = s;    t.v = e;    t.step = 0;    q.push(t);    while(!q.empty())    {        t = q.front();        q.pop();        if(str[t.u][t.v] == 'O')            return t.step;        for(int i = 0; i < 4; i++)  //四个方向搜索        {            x.u = t.u + xx[i];            x.v = t.v + yy[i];            if(x.u >= 0 && x.u < n && x.v >= 0 && x.v < m && str[x.u][x.v] != '#' && !map[x.u][x.v])            {                x.step = t.step + 1;                q.push(x);                map[x.u][x.v] = 1;            }        }    }    return 0;}int main(){    int t;    scanf("%d", &t);    while(t--)    {        scanf("%d%d", &n, &m);        memset(map, 0, sizeof(map));        int i, j;        int x, y;        for(i = 0; i < n; i++)            scanf("%s", str[i]);        for(i = 0; i < n; i++)            for(j = 0; j < m; j++)                if(str[i][j] == 'A')  //得到起点A                {                    x = i;                    y = j;                    break;                }        int re = BFS(x, y);        if(re == 0)            printf("-1\n");        else            printf("%d\n", re);    }    return 0;}