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

定义一个二维数组:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//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.
posted @   LYLtim  阅读(681)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示