迷宫问题

来源:互联网 发布:免费相册集制作软件 编辑:程序博客网 时间:2024/05/22 12:24

问题 C: 迷宫问题

时间限制1 Sec  内存限制32 MB
[提交][状态][讨论版]

题目描述

小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。
小明只能向上下左右四个方向移动。

输入

输入包含多组测试数据。输入的第一行是一个整数T,表示有T组测试数据。
每组输入的第一行是两个整数NM1<=N,M<=100)。
接下来N行,每行输入M个字符,每个字符表示迷宫中的一个小方格。
字符的含义如下:
‘S’:起点
‘E’:终点
‘-’:空地,可以通过
‘#’:障碍,无法通过
输入数据保证有且仅有一个起点和终点。

输出

对于每组输入,输出从起点到终点的最短路程,如果不存在从起点到终点的路,则输出-1

样例输入

1

5 5

S-###

-----

##---

E#---

---##

样例输出

9

 

题意概括:

算出从起点到终点最少需多少步

解题分析:

用广度优先搜索从起点开始搜索,当到达终点时结束搜索并输出步数,同时当无法到达终点时输出-1

 

测试样例:

2

5 5

S-###

-----

#####

E#---

---##

5 5

S-###

---##

###--

E#---

---##

测试样例输出:

-1

-1

代码:

#include<stdio.h>#include<string.h>#include<queue>using namespace std;struct note{    int x, y;};int m, n;int book[102][102];char Map[102][102];void bfs(note h, note t){    memset(book, 0, sizeof(book));    int Next[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};    int tx, ty, i;    note head, tail;    queue<note> q;    q.push(h);    book[h.x][h.y] = 1;    while(!q.empty()){        head = q.front();        q.pop();        for(i = 0; i < 4; i++){            tx = head.x + Next[i][0];            ty = head.y + Next[i][1];            if(tx < 0 || ty < 0 || tx >= n || ty >= m || Map[tx][ty] == '#')                continue;            if(!book[tx][ty]){                tail.x = tx;                tail.y = ty;                q.push(tail);                book[tx][ty] = book[head.x][head.y]+1;            }            if(tx == t.x && ty == t.y)                return ;        }    }}int main(){    int T, i, j;    note head, tail;    scanf("%d", &T);    while(T--){        scanf("%d%d", &n, &m);        getchar();        for(i = 0; i < n; i++){            for(j = 0; j < m; j++){                scanf("%c", &Map[i][j]);                if(Map[i][j] == 'S'){                    head.x = i;                    head.y = j;                }                else if(Map[i][j] == 'E'){                    tail.x = i;                    tail.y = j;                }            }            getchar();        }        bfs(head, tail);        printf("%d\n", book[tail.x][tail.y]-1);    }    return 0;}



原创粉丝点击