迷宮問題(bfs+路徑記錄)
阿新 • • 發佈:2018-12-09
思路:正常bfs搜尋,然後記錄每個點的父節點,最後找父節點,最後輸出路徑;
程式碼如下:
#include <iostream> #include <string> #include <vector> #include <set> #include <cstring> #include <climits> #include <algorithm> #include <cmath> #include <queue> #include <stdio.h> #define inf 429496729 using namespace std; int then[4][2] = { {-1,0},{0,-1},{0,1},{1,0} }; struct fnode { int x; int y; }ans[100]; struct node { int val; fnode ff; int x; int y; int step; }ma[5][5]; bool maa[5][5];//記錄有沒有走過 int main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { cin >> ma[i][j].val; ma[i][j].x = i; ma[i][j].y = j; } } queue<node>q; ma[0][0].step = 0; maa[0][0] = true; q.push(ma[0][0]); int flag = 0; while (!flag) { for (int i = 0; i < 4; i++) { int xx, yy; xx = q.front().x + then[i][0]; yy = q.front().y + then[i][1]; if (xx >= 5 || yy >= 5 || xx < 0 || yy < 0 || ma[xx][yy].val == 1 || maa[xx][yy]== true) continue; ma[xx][yy].step = ma[q.front().x][q.front().y].step+1; maa[xx][yy] = true; q.push(ma[xx][yy]); ma[xx][yy].ff.x = q.front().x; ma[xx][yy].ff.y = q.front().y; if (xx == 4 && yy == 4) { flag = 1; int ans_count = 0; fnode t; t.x = xx; t.y = yy; while (1) { ans[ans_count].x = t.x; ans[ans_count].y = t.y; ans_count++; if (t.x == 0 && t.y == 0) break; t = ma[t.x][t.y].ff; } for (int i = ans_count - 1; i >= 0; i--) { printf("(%d, %d)\n", ans[i].x, ans[i].y); } } } q.pop(); } system("pause"); return 0; }