使用c++構建帶環迴路迷宮,並使用迭代法,遞迴法求出口
使用遞迴方法求迷宮的最短路徑(其實在列印最短路徑是使用佇列的話路徑就不是反著的了)
#pragma once
#includeusing namespace std;
#include#includetypedef struct pos pos;
class solution
//判斷next是否可走
bool mazecheckisaccess(pos cur)
else
} //迭代法走迷宮
bool mazegetpath(pos path)
next = cur;
next._col -= 1;
if (mazecheckisaccess(next))
next = cur;
next._col += 1;
if (mazecheckisaccess(next))
next = cur;
next._row -= 1;
if (mazecheckisaccess(next))
next = cur;
next._row += 1;
if (mazecheckisaccess(next))
s.pop();
} return false;
} //遞迴法走迷宮
void mazegetpathr(pos path)
next = path;
next._col -= 1;
if (mazecheckisaccess(next))
next = path;
next._col += 1;
if (mazecheckisaccess(next))
next = path;
next._row -= 1;
if (mazecheckisaccess(next))
next = path;
next._row += 1;
if (mazecheckisaccess(next))
} //在求最短路徑時判斷next是否可走
bool mazecheckisaccess(pos next,pos cur)
else
} //求最短路徑
void mazegetshortpath(pos entry, stack& path)
else
path.push(entry);
if (next._col == _maze[0].size() - 1)
next = entry;
next._col -= 1;
if (mazecheckisaccess(next, entry))
next = entry;
next._col += 1;
if (mazecheckisaccess(next, entry))
next = entry;
next._row -= 1;
if (mazecheckisaccess(next, entry))
next = entry;
next._row += 1;
if (mazecheckisaccess(next, entry))
path.pop();
} //列印迷宮
void mazeprint()
cout << endl;
} cout << endl;
} //列印最短路徑
void mazeshortprint()
cout << "begin" << endl;
}public:
vector> _maze;
stackshortpath;
};void test() ,
, ,
, ,
, };
solution s(maze, );
s.mazeprint();
stackst;
s.mazegetshortpath(,st);
s.mazeprint();
s.mazeshortprint();
}
棧的應用之迷宮
棧是後進先出的,棧分為順序棧和鏈棧 順序棧是由一組位址連續的儲存單元構成,依次存放從棧底到棧頂的資料元素 鏈棧是一組位址可不連續的儲存單元構成,鏈棧的建立過程類似於採用前插法建立鍊錶 注意程式中棧的操作,push pop gettop 等等。網上有一段利用棧完成的程式,可以拿來欣賞一下,首先感謝一下...
棧的應用之迷宮
利用棧對迷宮求解,採用的基本方法是回溯法,其實也算是一種暴力破解吧.畢竟是將乙個乙個方塊檢驗直至終點或者棧空。入棧 當棧頂元素方塊周圍有可行方塊時,將該可行方塊入棧 出棧 當棧定元素的方塊周圍都沒有可行方塊時,出棧 有幾點需要注意 1.當棧頂元素彈出時,我們又要重新對棧頂元素周圍的方塊進行檢驗,為避...
迷宮問題 棧的應用
問題描述 以m n的矩陣表示迷宮圖,數字0代表通路,數字1代表障礙。對於走過的路徑,將數字0替換為數字2,便於檢視通路路徑。計算機解迷宮通常用的是 窮舉求解 方法,即從入口出發,順著某乙個方向進行探索,若能走通,則繼續往前進 否則沿著原路退回 回溯 換乙個方向繼續探索,直至出口位置,求得一條通路。注...