題目鏈接: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);
}