题目
题目描述
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
输入格式
一个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
样例输出
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
蒟蒻的代码:
/*
Name: LiHaoDa
Date: 21/06/24 16:17
*/
#include<bits/stdc++.h>
using namespace std;
int dis[100][100];
int a[100][100];
int visit[100][100];
int cmp;
int cnt;
int dx[100] = {0,1,0,-1};
int dy[100] = {1,0,-1,0};
struct node{
int x,y;
};
node record[27];
void bfs(){
queue<node> q;
visit[1][1] = 1;
q.push({1,1});
record[++cmp] = {1,1};
while(!q.empty()){
node now;
now = q.front();
if (now.x == 5&&now.y == 5) return;
//cout << now.x << ' ' << now.y << endl;
q.pop();
for(int i=0;i<4;++i){
int nx = now.x+dx[i];
int ny = now.y+dy[i];
if(nx>5||nx<1||ny>5||ny<1||visit[nx][ny] == 1||a[nx][ny] == 1) {
continue;
}
q.push({nx,ny});
record[++cmp] = {nx,ny};
//cout<< "record one" << endl;
visit[nx][ny] = 1;
dis[nx][ny] = dis[now.x][now.y]+1;
}
}
}
int main(){
for (int i=1;i<=5;++i){
for (int j=1;j<=5;++j){
cin >> a[i][j];
}
}
dis[1][1] = 1;
bfs();
// int maxx = 100;
// for(int i=1;i<=5;++i){
// for (int j=1;j<=5;++j){
// if(dis[i][j] <maxx) maxx = dis[i][j];
// }
// }
for(int i=1;i<=cmp;++i){
printf ("(%d,%d)\n",record[i].x-1,record[i].y-1);
}
}
求指导:怎么筛出最短路径上的点?