迷宫问题（求最短路径长度和最短路径）

```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,

};```

```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)```

``````#include<iostream>
using namespace std;
typedef struct S{
int x, y;
}S;
S s[100];
int num = 0;
int step[201][201];
char a[201][201];
int q1, q2, z1, z2;
int pd(int i, int j){
if (i < 0 || j < 0 || i >= 5 || j >= 5 || a[i][j] == '1')
return 0;
return 1;
}
void f(int i, int j, int n){
int x = step[i][j];
s[n].x = i;
s[n].y = j;
if (i == 4 && j == 4){
num = n;
return;
}
if (pd(i + 1, j)){
if (x + 1 < step[i + 1][j]){
step[i + 1][j] = x + 1;
f(i + 1, j, n + 1);
}
}
if (pd(i, j + 1)) {
if (x + 1 < step[i][j + 1]){
step[i][j + 1] = x + 1;
f(i, j + 1, n + 1);
}
}
if (pd(i - 1, j)){
if (x + 1 < step[i - 1][j]) {
step[i - 1][j] = x + 1;
f(i - 1, j, n + 1);
}
}
if (pd(i, j - 1)){
if (x + 1 < step[i][j - 1]){
step[i][j - 1] = x + 1;
f(i, j - 1, n + 1);
}
}
}
int main(){

for (int i = 0; i < 201; i++){
for (int j = 0; j < 201; j++)
step[i][j] = 10000;
}
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++)  {
cin >> a[i][j];
}
}
step[0][0] = 0;
f(0, 0, 0);
for (int i = 0;; i++){
printf("(%d, %d)\n", s[i].x, s[i].y);
if (s[i].x == 4 && s[i].y == 4)
break;
}
return 0;
}``````

原文作者：迷宫问题
原文地址: https://blog.csdn.net/qq_33193309/article/details/55099554
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。