hncu1102:迷宫问题(BFS)

http://hncu.acmclub.com/index.php?app=problem_title&id=111&problem_id=1102

题目描述

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

输入格式

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

输出

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

样例输入

1
5 5
S-###
-----
##---
E#---
---##

样例输出

9

 

 

简单BFS

 

#include 
#include 
#include 
using namespace std;

struct node
{
    int x,y,step;
};

char map[105][105];
int vis[105][105];
int to[4][2]= {1,0,-1,0,0,1,0,-1};
int n,m,sx,sy,ex,ey,ans;

int check(int x,int y)
{
    if(x<0 || x>=n || y<0 || y>=m)
        return 1;
    if(vis[x][y] || map[x][y]=='#')
        return 1;
    return 0;
}

void bfs()
{
    int i;
    queue Q;
    node a,next;
    a.x = sx;
    a.y = sy;
    a.step = 0;
    vis[a.x][a.y]=1;
    Q.push(a);
    while(!Q.empty())
    {
        a = Q.front();
        Q.pop();
        if(map[a.x][a.y]=='E')
        {
            ans = a.step;
            return ;
        }
        for(i = 0; i<4; i++)
        {
            next = a;
            next.x+=to[i][0];
            next.y+=to[i][1];
            if(check(next.x,next.y))
                continue;
            next.step=a.step+1;
            vis[next.x][next.y] = 1;
            Q.push(next);
        }
    }
    ans = -1;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        int i,j;
        for(i = 0; i


 

你可能感兴趣的:(搜索)