定義一個二維數組:
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<iostream>
#include<queue>
using namespace std;
const int MAX = 10;
int n=5, graph[MAX][MAX];
struct Position {
int x = 0, y = 0;
Position operator+(pair<int, int>& dir) {
return { x + dir.first,y + dir.second };
}
};
pair<int, int> dir[4] = { {1,0},{0,1},{0,-1},{-1,0} }; //順序不能亂,因爲0和4-1,1和4-2,方向相反,輸出時需要回溯
void print(Position pos) {
if (pos.x || pos.y) //回溯打印
print(pos + dir[4 + graph[pos.x][pos.y]]);
cout << "(" << pos.x << "," << pos.y << ")" << endl;
}
void bfs() {
Position start;
queue<Position> que;
que.push(start);
while (!que.empty()) {
for (int i = 0; i < 4; i++) {
Position pos = que.front() + dir[i];
if (pos.x >= 0 && pos.x < n && pos.y >= 0 && pos.y < n && !graph[pos.x][pos.y]) {
que.push(pos);
graph[pos.x][pos.y] -= (i + 1);
if (pos.x == n - 1 && pos.y == n - 1)
return;
}
}
que.pop();
}
}
int main() {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &graph[i][j]);
bfs();
print({ n - 1,n - 1 });
return 0;
}