迷宫问题-POJ 3984

时间:2023-02-03 06:19:11
迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 24348   Accepted: 14206

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 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 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<iostream>
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include<vector>
#include<queue>
using namespace std;
#define INF 0x3f3f3f3f
int map[][];//定义迷宫
int vis[][];//定义搜索遍历
int go[][]={{,-},{-,},{,},{,}};//方向数组,上下左右 typedef struct Node
{
int x;
int y;
}Node;
Node e;
queue <Node> q;
void BFS(Node s)//对迷宫进行广度优先搜索
{
q.push(s);//当前节点入队列
while(!q.empty())//当队列不为空时
{
Node cursor=q.front();
q.pop();//出队
if(cursor.x==e.x&&cursor.y==e.y)
{
return;
}
for(int i=;i<=;i++)
{
int x=cursor.x+go[i-][];//遍历上下左右四个方向
int y=cursor.y+go[i-][];
if(x>=&&x<&&y>=&&y<&&!map[x][y]&&!vis[x][y])//未访问
{
vis[x][y]=i;//i
Node temp;
temp.x=x;
temp.y=y;
q.push(temp);
}
}
}
} void print( int x,int y)
{
int prex,prey;
if(vis[x][y]!=-)
{ prex=x-go[vis[x][y]-][];//前驱x坐标
prey=y-go[vis[x][y]-][];//前驱y坐标
print(prex,prey);
}
printf("(%d, %d)\n",x,y);
} int main()
{
int i,j;
for(i=;i<;i++)
{
for(j=;j<;j++)
{
scanf("%d",&map[i][j]);
}
}
memset(vis,,sizeof vis);
e.x=;
e.y=;
Node s;
s.x=;
s.y=;
vis[s.x][s.y]=-;
BFS(s);
print(e.x,e.y);
return ;
}