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

定义一个二维数组:

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<stdio.h>

#include<stdlib.h>



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

	head = 0, tail = 1;



struct {char i, j;} que[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");

}



int main(void)

{

	while (head != tail) {

		head = (head + 1) % 23;

		char i;

		for (i = 0; i < 4; i++) {

			char Ni = que[head].i + Di[i], Nj = que[head].j + Dj[i];

			if (Ni >= 0 && Ni < 5 && Nj >= 0 && Nj < 5 && maze[Ni][Nj] == 0) {

					que[tail = (tail + 1) % 23].i = Ni;

					que[tail].j = Nj;

					maze[Ni][Nj] = 2;

					if (Ni == 4 && Nj == 4) {

						printf("Have path.\n"); exit(0);

					}

			}

		}

		print_maze();

	}

	printf("No path.\n");

	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
2 1 1 1 0
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 2 2 0 0
2 1 1 1 0
0 0 0 1 0
*********
2 1 0 0 0
2 1 0 1 0
2 2 2 0 0
2 1 1 1 0
2 0 0 1 0
*********
2 1 0 0 0
2 1 2 1 0
2 2 2 2 0
2 1 1 1 0
2 0 0 1 0
*********
2 1 0 0 0
2 1 2 1 0
2 2 2 2 0
2 1 1 1 0
2 2 0 1 0
*********
2 1 0 0 0
2 1 2 1 0
2 2 2 2 2
2 1 1 1 0
2 2 0 1 0
*********
2 1 2 0 0
2 1 2 1 0
2 2 2 2 2
2 1 1 1 0
2 2 0 1 0
*********
2 1 2 0 0
2 1 2 1 0
2 2 2 2 2
2 1 1 1 0
2 2 2 1 0
*********
2 1 2 0 0
2 1 2 1 2
2 2 2 2 2
2 1 1 1 2
2 2 2 1 0
*********
2 1 2 2 0
2 1 2 1 2
2 2 2 2 2
2 1 1 1 2
2 2 2 1 0
*********
2 1 2 2 0
2 1 2 1 2
2 2 2 2 2
2 1 1 1 2
2 2 2 1 0
*********
Have path.

你可能感兴趣的:(搜索)