迷宮問題(輸出路徑)

迷宮問題

Time Limit:
1000MS    Memory Limit:65536KB    64bit IO Format:%I64d & %I64u

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 0


Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

思路:題意很簡單,關鍵是用怎樣的方式將路徑保存下來,第一次接觸這種需要輸出路徑的題,參考了別人的方法。在結構體中用一個變量來保存當前狀態的上一個狀態,採用模擬隊列來實現出隊和入隊,用遞歸的方式來輸出途徑。

代碼如下:

#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"

using namespace std;

int top,rear;
int maze[10][10];
int movex[4] = {1,-1,0,0}; //x前進方式
int movey[4] = {0,0,1,-1}; //y前進方式

struct node
{
    int x,y,pre; //pre用來保存當前狀態的前一個狀態
}node[100];

bool is_block(int x,int y) //判斷當前位置能不能走
{
    if(x<0 || x>4 || y<0 || y>4)
    {
        return true;
    }
    if(maze[x][y])
    {
        return true;
    }
    return false;
}

void output(int i) //遞歸輸出走過的座標
{
    if(node[i].pre != -1)
    {
        output(node[i].pre);
        printf("(%d, %d)\n",node[i].x,node[i].y);
    }
}

void bfs(int x,int y)
{
    node[top].x = x;
    node[top].y = y;
    node[top].pre = -1;
    while(top < rear) //隊列不爲空
    {
        for(int i = 0;i < 4;i++)
        {
            int xx = movex[i]+node[top].x;
            int yy = movey[i]+node[top].y;
            if(xx == 4 && yy == 4) //走到迷宮的右下角,輸出路徑
            {
               output(top);
            }
            if(is_block(xx,yy))
            {
                continue;
            }
            else
            {
                maze[xx][yy] = 1; //走過的地方變爲1(牆壁),相當於標記爲已走過
                node[rear].x = xx;
                node[rear].y = yy;
                node[rear].pre = top;
                rear++; //入隊
            }
        }
        top ++; //出隊
    }
}

int main()
{
    while(~scanf("%d",&maze[0][0]))
    {
        for(int i = 1;i < 5;i++)
        {
            scanf("%d",&maze[0][i]);
        }
        for(int i = 1;i < 5;i++)
        {
            for(int j = 0;j < 5;j++)
            {
                scanf("%d",&maze[i][j]);
            }
        }
        top = 0,rear = 1;
        puts("(0, 0)");
        bfs(0,0);
        puts("(4, 4)");
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章