题意:输出从左上到右下的路径。
题解:BFS。也不解释了。唯一一点就是这个和我之前用队列模拟的查找路径不太一样。详细看代码拒接。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
int map[10][10]; // 地图
int book[10][10]; // 标记数组
int mov[4][2]={1,0,-1,0,0,1,0,-1}; // 移动数组
struct node {
int x;
int y;
};
node lu[10][10]; // 记录路径 记录该点是从那点得来的
queue<node> q;
void print(node s){ // DFS打印路径
if(s.x == 0 && s.y == 0){
printf("(%d, %d)\n",s.x,s.y);
return ;
}
print(lu[s.x][s.y]);
printf("(%d, %d)\n",s.x,s.y);
}
void bfs(){
book[0][0] = 1;
while(!q.empty()) q.pop();
node now ,next;
now.x = 0;
now.y = 0;
q.push(now);
while(!q.empty()){
now = q.front();
q.pop();
if(now.x == 4 && now.y == 4){ // 判断达到终点
//printf("GOOD GAME\n");
print(now);
}
for(int i = 0 ; i < 4 ; i ++){
next.x = now.x + mov[i][0];
next.y = now.y + mov[i][1];
if(next.x < 0 || next.y < 0 || next.x > 4 || next.y > 4 || book[next.x][next.y] || map[next.x][next.y]) // 判断是否可行
continue;
book[next.x][next.y] = 1;
lu[next.x][next.y] = now;
q.push(next);
}
}
}
int main(){
for(int i = 0 ; i < 5 ; i++){
for(int j = 0 ; j < 5 ; j++)
scanf("%d",&map[i][j]);
}
bfs();
}