迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10001 | Accepted: 5939 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 109
using namespace std;
int s[N][N];
int dis[4][2]={0,1,0,-1,1,0,-1,0};
int vis[N][N];
struct node
{
int x,y,pre;
}f[N];
void print(node t)
{
if(t.pre==-1)
{
printf("(%d, %d)\n",t.x-1,t.y-1);
return;
}
print(f[t.pre]);
printf("(%d, %d)\n",t.x-1,t.y-1);
}
void bfs()
{
int head=0,tail=0;
node t;
t.x=1;
t.y=1;
t.pre=-1;
f[tail++]=t;
while(head<tail)
{
node w=f[head];
for(int i=0;i<4;i++)
{
node e=w;
e.x+=dis[i][0];
e.y+=dis[i][1];
e.pre=head;
if(e.x>=1 && e.x<=5 && e.y>=1 && e.y<=5 && vis[e.x][e.y]==0 && s[e.x][e.y]==0)
{
vis[e.x][e.y]==1;
f[tail++]=e;
if(e.x==5 && e.y==5)
{
print(e);
return;
}
}
}
head++;
}
}
int main()
{
while(~scanf("%d",&s[1][1]))
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
if(i==1 && j==1) continue;
scanf("%d",&s[i][j]);
}
}
memset(vis,0,sizeof vis);
bfs();
}
return 0;
}