题目描述
迷宫是一个二维矩阵,其中1为墙,0为路,入口在第一列,出口在最后一列。
要求从入口开始,从出口结束,按照 上,下,左,右 的顺序来搜索路径.
输入
第一行输入迷宫大小N
第二行输入入口坐标
接下来n行输入完整迷宫
输出
输出完整棋盘,所有解法,走过的路用6表示。
样例输入
8
0 7
1 1 1 1 1 1 1 1
1 0 1 1 0 0 0 0
1 0 1 0 0 1 0 1
1 1 0 0 1 0 1 1
1 0 0 1 0 0 0 1
1 0 0 0 0 1 1 1
1 0 1 0 0 1 0 1
0 0 1 0 0 0 1 1
1 1 1 1 0 0 0 1
1 1 1 1 1 1 1 1
样例输出
1 1 1 1 1 1 1 1
1 0 1 1 6 6 6 6
1 0 1 6 6 1 0 1
1 1 6 6 1 0 1 1
1 6 6 1 0 0 0 1
1 6 0 0 0 1 1 1
1 6 1 0 0 1 0 1
6 6 1 0 0 0 1 1
1 1 1 1 0 0 0 1
1 1 1 1 1 1 1 1
实现代码
#include <stdio.h>
#define N 19 //整个迷宫大小(包括最外层墙壁)
char Maze[N][N] = {
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1},
{1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1},
{1,1,1,0,1,0,1,0,1,1,1,1,1,0,1,1,1,1,1},
{1,0,1,0,1,0,1,0,1,0,0,0,1,0,0,0,0,0,1},
{1,0,1,0,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1},
{1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1},
{1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,1},
{1,0,1,0,1,1,1,0,0,0,1,0,1,0,1,0,1,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,1,0,1},
{1,0,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,0,1},
{1,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,1},
{1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,1},
{0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
};
char step[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; //定义四个方向
int count = 0;
char Check(char i, char j) //判断下一步是不是通路
{
if(i >= 0 && i<=18 && j >= 0 && j <= 18)
{
if(0 == Maze[i][j])
{
return 1;
}
}
return 0;
}
void Display(void)
{
char i, j;
for(i=0; i<N; ++i)
{
for(j=0; j<N; ++j)
{
printf("%d", Maze[i][j]);
}
printf("\n");
}
}
void Find(char ci, char cj)
{
char n;
if((N-1) == cj) //这个边界设置得比较粗糙,到N-1这个下标就算终点,没想到什么好的办法
{
Maze[ci][cj] = 6; //终点的最后一个6
printf("解法%d(Enter回车查看下一解法):\n", ++count);
Display();
getchar();
Maze[ci][cj] = 0;
}
else
{
for(n=0; n<4; ++n)
{
if(Check(ci+step[n][0], cj+step[n][1])) //依然用Check实现判断:是否可以在某个方向走下一步
{
Maze[ci][cj] = 6; //6表示走过的路
Find(ci+step[n][0], cj+step[n][1]);
Maze[ci][cj] = 0; //传统回溯方法
}
}
}
}
int main(void)
{
printf("\t迷宫问题(1 墙壁 0 道路 6 解法)\n\n");
printf("原迷宫(Enter回车查看解法):\n");
Display();
getchar();
//(17, 0)为起点
Find(17, 0);
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-09 00:56:26