hncu1102:迷宮問題(BFS)

來源:互聯網
上載者:User
文章目錄
  • 題目描述
  • 輸入格式
  • 輸出
  • 範例輸入
  • 範例輸出
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 <stdio.h>#include <string.h>#include <queue>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<node> 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<n; i++)            scanf("%s",map[i]);        for(i = 0; i<n; i++)        {            for(j = 0; j<m; j++)            {                if(map[i][j]=='S')                {                    sx = i;                    sy = j;                }            }        }        memset(vis,0,sizeof(vis));        bfs();        printf("%d\n",ans);    }    return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.