poj3984 迷宫问题(BFS)

来源:互联网 发布:淘宝收藏标签看不到 编辑:程序博客网 时间:2024/05/29 04:37
迷宫问题
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 6688 Accepted: 3905

Description

定义一个二维数组:
int maze[5][5] = {0, 1, 0, 0, 0,0, 1, 0, 1, 0,0, 0, 0, 0, 0,0, 1, 1, 1, 0,0, 0, 0, 1, 0,};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0

Sample Output

(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4)

 

#include<stdio.h>#include<string.h>bool s[5][5];int son[5][5];int dir[4][2]= {0,-1,0,1,1,0,-1,0};struct node{    int x,y;} q[30];void bfs(int x,int y){    int i,nx,ny,fro=0,rea=1;    node tem;    q[0].x=x;    q[0].y=y;    while(fro<rea)    {        tem=q[fro++];        for(i=0; i<4; i++)        {            nx=tem.x+dir[i][0];            ny=tem.y+dir[i][1];            if(nx>=0&&nx<5&&ny>=0&&ny<5&&s[nx][ny]==0)            {                son[nx][ny]=tem.x*5+tem.y;//用一维存二维                q[rea].x=nx;                q[rea++].y=ny;                s[nx][ny]=1;            }        }    }}int main(){    int i,j;    for(i=0; i<5; i++)        for(j=0; j<5; j++)            scanf("%d",&s[i][j]);    s[4][4]=1;    bfs(4,4);    //从终点走向起点,因为每步的入度只有一个,而出度可达四个之多,所以我们记录每一步的入度,即记录了路径    printf("(0, 0)\n");    i=j=0;    while(i+j!=8)    {        int tem=son[i][j];        i=tem/5;        j=tem%5;        printf("(%d, %d)\n",i,j);    }    return 0;}


 

0 0
原创粉丝点击