题目链接:http://poj.org/problem?id=3984
Time Limit: 1000MS | Memory Limit: 65536K |
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 0Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct Node {
int x,y,f;
}a[26];
void OutPut(int n)
{
if(n == -1)
return;
OutPut(a[n].f);
cout << "("<< a[n].x << ", " << a[n].y << ")" << endl;
}
int main()
{
int maze[5][5];
bool book[5][5];
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin >> maze[i][j];
int next[4][2] = {{0,1},
{1,0},
{0,-1},
{-1,0}};
memset(book,false,sizeof book);
int head=0;
int tail=0;
a[tail].x=0;
a[tail].y=0;
a[tail].f=-1;
book[0][0]=true;
tail++;
int tx,ty;
bool flag = false;
while(head < tail)
{
for(int i=0;i<=3;i++)
{
tx=a[head].x+next[i][0];
ty=a[head].y+next[i][1];
if( tx > 4 || tx < 0 || ty > 4 || ty <0)
continue;
if(maze[tx][ty]==0 && !book[tx][ty])
{
a[tail].x=tx;
a[tail].y=ty;
a[tail].f=head;
book[tx][ty]=true;
tail++;
if(tx == 4 && ty == 4)
{
flag=true;
break;
}
}
}
if(flag)
break;
head++;
}
tail--;
OutPut(tail);
}