运用队列迷宫求解。
- #include <stdio.h>
- #include "stdlib.h"
- #define MAXSIZE 150
- int mg2[10][10] = {
- {1,1,1,1,1,1,1,1,1,1},
- {1,0,0,1,0,0,0,1,0,1},
- {1,0,0,1,0,0,0,1,0,1},
- {1,0,0,0,0,1,1,0,0,1},
- {1,0,1,1,1,0,0,0,0,1},
- {1,0,0,0,1,0,0,0,0,1},
- {1,0,1,0,0,0,1,0,0,1},
- {1,0,1,1,1,0,1,1,0,1},
- {1,1,0,0,0,0,0,0,0,1},
- {1,1,1,1,1,1,1,1,1,1}
- };
- struct node
- {
- int i,j,pre,di;
- }sq[MAXSIZE];
- void print(int front)
- { int pre = sq[front].pre;
- printf("倒着输出的路径为: \n");
- while(pre != -1)
- {
- printf("i = %d ,j = %d ,di = %d\n",sq[pre].i, sq[pre].j, sq[pre].di);
- pre = sq[pre].pre;
- }
- printf("\n\n");
- }
- void mgpath2(int x1, int y1, int x2, int y2)
- {
- int front = -1; int rear = -1; int find = 0; int i,j; //front rear 是队列的头部和尾部
- rear++;
- sq[rear].i = i = x1; sq[rear].j = j = y1; sq[rear].di = -1; sq[rear].pre = -1; //把开始的节点进队列,并初始化前一节点的下标和方向为 -1
- mg2[i][j] = -1;
- while(front <= rear) //当队列中还有元素的时候进行循环
- {
- front ++ ;
- find = 0; //出队列
- if(sq[front].i == x2 && sq[front].j == y2) //判断到达目标的时候,打印输出路径
- {
- printf(front); //此处没有直接返回 ,是想要打印全部的路径,但是目的没有达到,因为走过的节点被赋值为-1,也就不能再走一次,所以不能实现打印所有路径
- }
- while(sq[front].di < 4 && find == 0) //此处得循环必须是四次,因为要把周围能走的坐标点都进入队列
- { sq[front].di ++;
- switch(sq[front].di)
- {
- case 0 :
- i = sq[front].i - 1; j = sq[front].j ; if(mg2[i][j] == 0) find = 1; break;
- case 1 :
- i = sq[front].i; j = sq[front].j + 1 ; if(mg2[i][j] == 0) find = 1; break;
- case 2 :
- i = sq[front].i + 1; j = sq[front].j ; if(mg2[i][j] == 0) find = 1; break;
- case 3 :
- i = sq[front].i; j = sq[front].j - 1; if(mg2[i][j] == 0) find = 1; break;
- }
- if(find == 1) //此处根据find的值判断是否找到可走的元素,然后根据情况判断是否应该如队列
- {
- rear++;
- mg2[i][j] = -1;
- sq[rear].i = i; sq[rear].j = j; sq[rear].di = -1; sq[rear].pre = front;
- }
- find = 0;
- }
- }
- }
- //广度遍历
- void main()
- {
- mgpath2(1,1,8,8);
- }