http://poj.org/problem?id=3984

 

定义一个二维数组: 

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 <cstdio>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <queue>
#include <algorithm>
using namespace std;
#define maxn 521
#define INF 0xfffffff
int maps[maxn][maxn];
int dir[4][2]= {{0,1},{1,0},{-1,0},{0,-1}};

struct node
{
    int x, y;
}a[maxn][maxn];

void DFS(int x, int y)
{
    if(x == 0 && y == 0)
    {
        printf("(0, 0)\n");
        return ;
    }

    DFS(a[x][y].x, a[x][y].y);

    printf("(%d, %d)\n",x, y);
}
void BFS()
{
    int i;
    queue<node>Q;
    node begins, now, next;

    begins.x = 0;
    begins.y = 0;

    Q.push(begins);

    while(Q.size())
    {
        now = Q.front();
        Q.pop();

        if(now.x == 4 && now.y == 4)
            return ;

        for(i=0; i<4; i++)
        {
            next.x = now.x + dir[i][0];
            next.y = now.y + dir[i][1];

            if(next.x>=0 && next.x<5 && next.y>=0 && next.y<5 && !maps[next.x][next.y])
            {
                maps[next.x][next.y]=1;
                a[next.x][next.y] = now;
                Q.push(next);
            }
        }
    }

}

int main()
{
    int i,j;

    for(i=0; i<5 ; i++)
    for(j=0; j<5; j++)
    scanf("%d", &maps[i][j]);

    BFS();
    DFS(4, 4);

    return 0;
}
View Code

 

 
posted on 2016-07-19 08:51  不忧尘世不忧心  阅读(239)  评论(0编辑  收藏  举报