寒假補充專案-回溯法走迷宮

不被看好的青春叫成長發表於2015-01-31
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;

#define MaxSize 100
int maze[10][10] =   //定義一個迷宮,0表示通道,1表示牆
{
    {1,1,1,1,1,1,1,1,1,1},
    {1,0,0,1,1,0,0,1,0,1},
    {1,0,0,1,0,0,0,1,0,1},
    {1,0,0,0,0,1,1,0,0,1},
    {1,0,1,1,1,0,0,0,0,1},
    {1,0,0,0,1,0,0,0,0,1},
    {1,0,1,0,0,0,1,0,0,1},
    {1,0,1,1,1,0,1,1,0,1},
    {1,1,0,0,0,0,0,0,0,1},
    {1,1,1,1,1,1,1,1,1,1}
};

struct Try //定義一個棧,儲存路徑
{
    int i;               //當前方塊的行號
    int j;               //當前廣場的列號
    int d;              //di是下一可走方位的方位號
} path[MaxSize];         //定義棧

int top = -1;            //初始化棧指標

void findPath(int xb, int yb, int xe, int ye)            //路徑為從(xb,yb)到(xe,ye)
{
    int i, j, d, find, k;
    top++;                                             //初始方塊進棧
    path[top].i = xb;
    path[top].j = yb;
    path[top].d = -1;
    maze[xb][yb] = -1;
    while(top>-1)                                      //棧不為空時迴圈
    {
        i = path[top].i;
        j = path[top].j;
        d = path[top].d;
        if(i==xe && j==ye)                             //找到了出口,輸出路徑
        {
            cout << "迷宮路徑如下:\n";
            for(k=0; k<=top; k++)
            {
                cout << "\t(" << path[k].i << "," << path[k].j << ")";
                if((k+1)%5==0) cout << endl;            //每輸出五個方塊後換一行
            }
            cout << endl;
            return;
        }
        find = 0;
        while(d<4 && find==0)                          //找下一個可走的點
        {
            d++;
            switch(d)
            {
            case 0:  //向上
                i = path[top].i-1;
                j = path[top].j;
                break;
            case 1: //向右
                i = path[top].i;
                j = path[top].j+1;
                break;
            case 2:  //向下
                i = path[top].i+1;
                j = path[top].j;
                break;
            case 3:  //向左
                i = path[top].i;
                j = path[top].j-1;
                break;
            }
            if(maze[i][j]==0) find = 1;                      //找到通路
        }
        if(find==1)                                        //找到了下一個可走方塊
        {
            path[top].d = d;                               //修改原棧頂元素的d值
            top++;                                         //下一個可走方塊進棧
            path[top].i = i;
            path[top].j = j;
            path[top].d = -1;
            maze[i][j] = -1;                                 //避免重複走到這個方塊
            //cout << "\t(" << path[top].i << "," << path[top].j << ")"; //顯示經過的試探
        }
        else  //沒有路可走,則退棧
        {
            maze[path[top].i][path[top].j] = 0;                  //讓該位置變成其它路徑可走方塊
            top--;
        }
    }
    cout << "沒有可走路徑!\n";
}

int main()
{
    findPath(1,1,8,8);  //從(1,1)入,(8,8)出
    return 0;
}

相關文章