用深度优先搜索解迷宫问题

定义一个二维数组:

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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的路线。程序如下:

//By LYLtim

#include
#include

const char
	Di[4] = {0,1,0,-1},
	Dj[4] = {1,0,-1,0};

char maze[5][5] = {
	2, 1, 0, 0, 0,
	0, 1, 0, 1, 0,
	0, 0, 0, 0, 0,
	0, 1, 1, 1, 0,
	0, 0, 0, 1, 0},
	ip = 0;

struct {char i, j;} path[23];

void print_maze(void)
{
	char i, j;
	for (i = 0; i < 5; i++) {
		for (j = 0; j < 5; j++)
			printf("%hd ", maze[i][j]);
		putchar('\n');
	}
	printf("*********\n");
}

void print_path(void)
{
	char i = 0;
	printf("(0,0)");
	for (i = 0; i < ip; i++)
		printf("->(%hd,%hd)", path[i].i, path[i].j);
	exit(0);
}

void try(char i, char j)
{
	char k;
	for (k = 0; k < 4; k++) {
		char Ni = i + Di[k], Nj = j + Dj[k];
		if (Ni >= 0 && Ni <5 && Nj >= 0 && Nj < 5 && maze[Ni][Nj] == 0) {
			maze[Ni][Nj] = 2;
			path[ip++].i = Ni; path[ip].j = Nj;
			print_maze();
			if (Ni == 4 && Nj == 4)
				print_path();
			else
				try(Ni, Nj);
			maze[Ni][Nj] = 0;
			path[--ip].i = 0; path[ip].j = 0;
		}
	}
}
		

int main(void)
{
	try(0, 0);
	return 0;
}

 

运行结果如下:

2 1 0 0 0 
2 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 0 0 0 0
0 1 1 1 0
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 2 0 0 0
0 1 1 1 0
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 2 2 0 0
0 1 1 1 0
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 2 2 2 0
0 1 1 1 0
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 2 2 2 2
0 1 1 1 0
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 2 2 2 2
0 1 1 1 2
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 2 2 2 2
0 1 1 1 2
0 0 0 1 2
*********
(0,0)->(1,0)->(2,0)->(2,0)->(2,1)->(2,2)->(2,3)->(3,4)->(4,4)

转载于:https://www.cnblogs.com/LYLtim/archive/2011/10/15/2212844.html

你可能感兴趣的:(用深度优先搜索解迷宫问题)