15×15 迷宮,1 為牆,0 為路,2 起點,3 終點。分別用棧(深度優先)和隊列(廣度優先)找路徑並標記輸出。
#include#include #include using namespace std; const int N = 15; int maze[N][N] = { ... }; // 迷宮數據 struct Point { int x, y; }; void findStartEnd(Point& s, Point& e) { ... } void initMaze() { ... } // 恢復原始數據 void dfsWithStack(Point s, Point e) { ... } // 棧版邏輯 void bfsWithQueue(Point s, Point e) { ... } // 隊列版邏輯 void printPathDFS(Point s) { ... } // 從起點順向輸出 void printPathBFS(Point e) { ... } // 從終點逆向輸出 int main() { Point start, end; findStartEnd(start, end); dfsWithStack(start, end); printPathDFS(start); initMaze(); bfsWithQueue(start, end); printPathBFS(end); return 0; }
完整代碼較長,核心在於權值標記策略與路徑回溯方式的差異。DFS 適合找任意一條路,BFS 保證最短路徑。