简单搜索,用一个结构体栈来储存临时路径,一个结构体数组来存储最短路径,实时更新最短路径的结构体数组,最后输出
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 5
struct step {
int tx;
int ty;
}s[10000], t[10000];
int sizee = sizeof(t);
int maze[N][N];
int cou, minn; ///cou 为栈顶,minn为走的最小步数
int next[4][2] = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} }; ///上下左右四个方向
bool check(int x, int y) ///检查是否标记过,是否越界
{
if (x >= N || x < 0 || y >= N || y <0 || maze[x][y]) return false;
return true;
}
void dfs(int x, int y, int dep) ///dep标记走的步数
{
int i;
if (dep > minn) return ; ///剪枝,当途中步数大于最小步数的时候没必要继续了
if (x == 4 && y == 4) { ///若抵达终点且步数小于minn,更新minn,并将栈拷贝到数组,若无更小最后输出s
if (dep < minn) {
minn = dep;
memcpy(s, t, sizee);
}
return ;
}
for (i = 0; i < 4; i++) {
int nx = x + next[i][0];
int ny = y + next[i][1];
if (!check(nx, ny)) continue; ///越界与标记检查
t[cou].tx = nx; ///入栈
t[cou++].ty = ny;
maze[nx][ny] = 1; ///标记为已经走过
dfs(nx, ny, dep + 1); ///dfs
maze[nx][ny] = 0; ///回溯
cou--; ///伴随回溯,弹出栈顶元素
}
}
int main()
{
int i, j;
int x = 0, y = 0;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
scanf("%d", &maze[i][j]);
}
}
cou = 0;
minn = 99999999;
t[cou].tx = x; ///将(0, 0)先入栈
t[cou++].ty = y;
maze[0][0] = 1; ///标记起点
dfs(x, y, 1); ///1刚好也是栈内元素数
for (i = 0; i < minn; i++) {
printf("(%d, %d)\n", s[i].tx, s[i].ty); ///此时s内储存的就是最短路径
}
return 0;
}