参考博客:https://blog.youkuaiyun.com/tsaid/article/details/6856795
定义一个二维数组:
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;
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,
};
int dir[4][2]={{1,0},{0,-1},{0,1},{-1,0}};
int book[5][5];
int pre[25];
bool check(int x, int y){
if(x >= 0 && x < 5 && y >= 0 && y < 5)
return true;
return false;
}
void bfs(){
queue<int> q;
int row = 0;
int col = 0;
int cur = row*5+col;
book[0][0] = 1;
pre[0] = -1;
q.push(cur);
while(!q.empty()){
cur = q.front();
q.pop();
for(int i = 0; i < 4; i++){
row = cur/5 + dir[i][0];
col = cur%5 + dir[i][1];
if(check(row, col) && maze[row][col] == 0 && book[row][col] == 0){
int next = row*5+col;
pre[next] = cur;
if(next == 24)
return ;
q.push(next);
book[row][col] = 1;
}
}
}
}
void print(int x){
if(pre[x] != -1)
print(pre[x]);
cout << "(" << x/5 << ", " << x%5 << ")" << endl;
}
int main(){
bfs();
print(24);
return 0;
}