这个算是完全自己写的
- /*广度优先�索求解迷宫*/
- #include<stdio.h>
- #define MAX_ROW 5
- #define MAX_COL 5
- #define LEN 512
- typedef struct
- {
- int row;
- int col;
- int pre;/*the front node, saved the subscript of the queue array*/
- }point;
- point queue[LEN];
- int tail = 0, head = 0;
- point start = {0, 0, -1};
- point target = {4, 4, -1};
- void in_queue(point item)
- {
- queue[tail++] = item;
- }
- point out_queue(void)
- {
- return queue[head++];
- }
- int is_empty(void)
- {
- return head == tail;
- }
- 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}
- };
- /*ä¸?能使用æ¤æ–¹æ³•ï¼Œå› 为并å?‘çš„æ?œç´¢å?¯èƒ½å¯¼è‡´æŸ?节点的å‰?驱改å?˜*/
- //int front[MAX_ROW][MAX_COL] = {0};
- void print_maze(void)
- {
- int i, j;
- for(i = 0 ; i < MAX_ROW; i++)
- {
- for(j = 0; j < MAX_COL; j++)
- {
- printf("%d ", maze[i][j]);
- }
- putchar('/n');
- }
- }
- void print_queue()
- {
- int i;
- printf("/nthe queue info:/n");
- for(i = 0; i < tail; i++)
- {
- printf("(%d,%d,%d) ", queue[i].row, queue[i].col, queue[i].pre);
- }
- printf("/n##############################/n");
- }
- void visit(int row, int col)
- {
- point tmp = {row, col, head - 1};
- maze[row][col] = 2;
- in_queue(tmp);
- }
- void print_way(void)
- {
- point tmp = queue[tail - 1];
- while(!(tmp.row == start.row && tmp.col == start.col))
- {
- // getchar();
- printf("(%d,%d)/n", tmp.row, tmp.col);
- tmp = queue[tmp.pre];
- // print_queue();
- }
- printf("(%d,%d)/n", start.row, start.col);
- }
- int main(void)
- {
- point p = start;
- maze[start.row][start.col] = 2;
- in_queue(p);
- while(!(is_empty()))
- {
- p = out_queue();
- print_maze();
- // print_queue();
- // getchar();
- if((p.row == target.row) && (p.col == target.col))
- {
- static int count = 0;
- printf("%d way:/n", ++count);
- print_way();
- break;
- // back_track(p);
- }
- if((p.row - 1 >= 0) && (maze[p.row - 1][p.col] == 0))/*found the up way*/
- {
- visit(p.row - 1, p.col);
- }
- if((p.col + 1 < MAX_COL) && (maze[p.row ][p.col + 1] == 0))/*found the left way*/
- {
- visit(p.row, p.col + 1);
- }
- if((p.col - 1 >= 0) && (maze[p.row][p.col - 1] == 0))/*found the right way*/
- {
- visit(p.row, p.col - 1);
- }
- if((p.row + 1 < MAX_ROW) && (maze[p.row + 1][p.col] == 0))/*found the down way*/
- {
- visit(p.row + 1, p.col);
- }
- }
- if(!((p.row == target.row) && (p.col == target.col)))
- {
- printf("Can not found!/n");
- }
- return 0;
- }