poj3984 迷宫问题

来源:互联网 发布:sopcast这款网络电视 编辑:程序博客网 时间:2024/06/07 14:38
迷宫问题
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11428 Accepted: 6821

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<queue>#include<algorithm>#include<iostream>using namespace std;int dx[4]={1,0,0,-1};//四个方向 int dy[4]={0,1,-1,0};int f=0,r=1;int  map[5][5]; struct line{int x,y,t;}road[1000],temp;bool judge(line a)//判断是否出界或是走过 {return a.x >=0&&a.x <5&&a.y >=0&&a.y <5&&!map[a.x ][a.y ];}void PRINTF(int i)//递归输出路径 {if(road[i].t!=-1){PRINTF(road[i].t );printf("(%d, %d)\n",road[i].x,road[i].y  );}}void bfs(){road[f].x =0;road[f].y =0;road[f].t =-1;while(f<r)//控制并记录路径 {for(int i=0;i<4;i++)  {  temp.x =road[f].x +dx[i];  temp.y =road[f].y +dy[i];  if(!judge(temp))  continue;  else  {  map[temp.x ][temp.y ]=1;  road[r].x =temp.x ;      road[r].y=temp.y;      road[r].t= f;      r++;}if(temp.x ==4&&temp.y ==4)PRINTF(f);  }f++;}}int main(){for(int i=0;i<5;i++)  for(int j=0;j<5;j++)     scanf("%d",&map[i][j]);     printf("(0, 0)\n");     bfs();     printf("(4, 4)\n");return 0;}
</pre>
1 0