迷宫问题,C语言解决
程序员文章站
2022-05-20 21:35:28
...
迷宫问题
递归求解
问题描述:有一个7*8的网格,要求求出最短路径
算法:第一种解:给最外层加层墙,让他都有四个方向,然后判断有路并且未走过,就走
递归,有值返回,根据值判断是否调用输出。
第二种解:给最外层加层墙,让他都有四个方向,然后判断有路并且未走过,就走
递归,调用时判断是否出口是则,调用输出返回。
#include<stdio.h>
#include<stdlib.h>
#define R 7
#define C 8
int move[4][2] = { {1,0},
{0,1},
{-1,0},
{0 - 1}
};//存放四个方向
int stack[200][2] = { {-1,-1} };//存放路经
int top = -1;
int m[R + 2][C + 2] = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,1,1,0,0,1},
{1,0,1,0,0,1,0,0,1,1},
{1,0,1,0,0,0,0,1,1,1},
{1,0,0,1,0,1,0,1,1,1},
{1,1,0,1,1,1,0,1,1,1},
{1,0,0,1,0,0,0,1,1,1},
{1,1,0,0,0,1,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};-
int t[R + 2][C + 2] = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,1,1,0,0,1},
{1,0,1,0,0,1,0,0,1,1},
{1,0,1,0,0,0,0,1,1,1},
{1,0,0,1,0,1,0,1,1,1},
{1,1,0,1,1,1,0,1,1,1},
{1,0,0,1,0,0,0,1,1,1},
{1,1,0,0,0,1,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};//用来查看是否走过
//输出一组解
int Maze_1(int x, int y)
{
int a, b,tag;
if (x == 7 && y == 8)
return 1;
for (int i = 0; i < 4; i++)
{
a = x + move[i][0];
b = y + move[i][1];
//有路并且没走过
if (!m[a][b] && !t[a][b])
{
t[a][b] = 1;
tag = Maze_1(a, b);
if (tag == 1)
{
printf("[%d,%d]\t",a,b);
return 1;
}
}
}
return 0;
}
void print()
{
for (int i=0; i<=top; top++)
{
printf("[");
for (int j = 0; j < 2; j++)
{
printf("%d", stack[i][j]);
}
printf("]\t");
}
printf("\n");
}
//输出所有解,但是并没有输出最优解
void Maze_2(int x, int y)
{
int a, b;
if (x == 7 && y == 8)
print();
else
{
for (int i = 0; i < 4; i++)
{
a = x + move[i][0];
b = y + move[i][1];
if (!m[a][b] && !t[a][b])
{
t[a][b] = 1;
top++;
stack[top][0] = a;//借助栈存储走过的路经
stack[top][1] = b;
Maze_2(a, b);
t[a][b]=0;
top--;
}
}
}
}
int main(void)
{
// Maze_1(1, 1);
Maze_2(1, 1);
// printf("[1,1]");
}
上一篇: Dijkstra--vector实现