按规矩先上图
环形队列的最少元素数量,即为时序上最宽出元素数量即可
因为探索完A层即可弹出探索下一层B, 只需要最宽一层满足,其他层级都满足
为了检验该想发,编写程序验证即可
环形队列的检测和空队、满队的测试警告用数量标记法
/*
* 广度优先算法解决迷宫问题
*/
#include <stdio.h>
#define MAX_ROW 5
#define MAX_COL 5
#define MAX_LEN 3
/*
* 迷宫图, 1表示障碍, 0表示路径, 只允许上下左右移动
*/
int maze[MAX_ROW][MAX_COL] = {
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, //
};
struct point {
int row;
int col;
};
struct point queue[MAX_LEN];
int head = 0, tail = 0;
int queue_len = 0;
void enqueue(struct point p);
struct point dequeue(void);
void print_maze(void);
void visit(int row, int col);
int main(int argc, char *argv[]) {
struct point p = {
0,
0,
};
maze[p.row][p.col] = 2;
enqueue(p);
while (queue_len != 0) {
p = dequeue();
if (p.row == MAX_ROW - 1 && p.col == MAX_COL - 1) {
printf("there is a path!");
break;
}
if (p.row + 1 <= MAX_ROW - 1 && maze[p.row + 1][p.col] == 0)
visit(p.row + 1, p.col);
if (p.row - 1 >= 0 && maze[p.row - 1][p.col] == 0)
visit(p.row - 1, p.col);
if (p.col + 1 <= MAX_COL - 1 && maze[p.row][p.col + 1] == 0)
visit(p.row, p.col + 1);
if (p.col - 1 >= 0 && maze[p.row][p.col - 1] == 0)
visit(p.row, p.col - 1);
print_maze();
}
return 0;
}
void enqueue(struct point p) {
if (queue_len == MAX_LEN) {
printf("full of queue, cannot enqueue!\n");
return;
}
queue_len++;
queue[tail++ % MAX_LEN] = p;
}
struct point dequeue(void) {
if (queue_len == 0) {
printf("empty queue, cannot dequeue!\n");
return queue[head];
}
queue_len--;
return queue[head++ % MAX_LEN];
}
void print_maze(void) {
for (int i = 0; i < MAX_ROW; i++) {
for (int j = 0; j < MAX_COL; j++)
printf("%d", maze[i][j]);
printf("\n");
}
printf("**********\n");
}
void visit(int row, int col) {
struct point visit_point = {
row,
col,
};
maze[row][col] = 2;
enqueue(visit_point);
}
结果
21000
21010
00000
01110
00010
**********
21000
21010
20000
01110
00010
**********
21000
21010
22000
21110
00010
**********
21000
21010
22000
21110
20010
**********
21000
21010
22200
21110
20010
**********
21000
21010
22200
21110
22010
**********
21000
21210
22220
21110
22010
**********
21000
21210
22220
21110
22210
**********
21200
21210
22220
21110
22210
**********
21200
21210
22222
21110
22210
**********
21200
21210
22222
21110
22210
**********
21220
21210
22222
21110
22210
**********
21220
21212
22222
21112
22210
**********
21222
21212
22222
21112
22210
**********
21222
21212
22222
21112
22212
**********
21222
21212
22222
21112
22212
**********
21222
21212
22222
21112
22212
**********
there is a path!
全程没有警告,OK成功