POJ - 3984 DFS记录路径

定义一个二维数组: 

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 <cstring>
#include <stack>
using namespace std;
struct Node
{
    int x,y,pre;
};
int main()
{
    int maze[5][5];
    int flog[5][5];
    memset(flog,1,sizeof(flog));
    for(int i=0;i < 5;i++)
    {
        for(int j=0;j < 5;j++)
            cin >> maze[i][j];
    }

    Node que[50];
    int front,rear;
    front = rear = 0;

    int M[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
    que[0].x=0;que[0].y=0;que[0].pre=-1;
    flog[0][0]=0;

    int x,y;
    while(front <= rear)
    {
        for(int i=0;i < 4;i++)
        {
            x=que[front].x + M[i][0];
            y=que[front].y + M[i][1];
            if(x>=0&&x<5&&y>=0&&y<5)
            {
                if(maze[x][y]==0&&flog[x][y])
                {
                    rear++;
                    que[rear].x=x;
                    que[rear].y=y;
                    que[rear].pre=front;
                    flog[x][y]=0;
                }
            }
            if(x==4&&y==4)
                break;
        }
        if(x==4&&y==4)
            break;
        front++;
    }
    stack<int>s1,s2;
    int k = rear;
    while(que[k].pre!=-1)
    {
        s1.push(que[k].x);
        s2.push(que[k].y);
        k=que[k].pre;
    }
    cout << "(0, 0)" << endl;
    while(!s1.empty())
    {
        cout << '(' << s1.top() << ", " << s2.top() << ")" << endl;
        s1.pop();s2.pop();
    }
    return 0;
}

  

posted @ 2017-02-17 15:48  呆毛王王负剑  阅读(68)  评论(0)    收藏  举报