运用栈迷宫求解。
- #include <stdio.h>
- #define MAXSIZE 150
- struct
- {
- int i; int j; int di;
- }st[MAXSIZE];
- int mg[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}
- };
- void mgpath(int x1, int y1, int x2, int y2)
- {
- int i,j, di, find, k, top = -1;
- top++;
- st[top].i = i = x1; st[top].j = j = y1; st[top].di = di = -1;
- mg[x1][y1] = -1;
- while(top > -1)
- {
- if(st[top].i == x2 && st[top].j == y2) //用来判读是否到达出点
- {
- for(k = 0; k <= top; k++)
- printf("i = %d , j = %d , di = %d .\n",st[k].i, st[k].j, st[k].di);
- return ;
- }
- find = 0; //标志用来表示是否 找到下一个节点,要是找到那么 使其进栈,否则出栈节点并且把出栈节点相应的坐标值重新赋予 0 ,使其可走
- while(find ==0 && st[top].di < 4)
- {
- st[top].di ++;
- switch(st[top].di)
- {
- case 0:
- i = st[top].i -1 ; j = st[top].j; if(mg[i][j] == 0) find = 1;break;
- case 1:
- i = st[top].i ; j = st[top].j + 1; if(mg[i][j] == 0) find = 1; break;
- case 2:
- i = st[top].i + 1; j = st[top].j ; if(mg[i][j] == 0) find = 1; break;
- case 3:
- i = st[top].i ; j = st[top].j -1 ; if(mg[i][j] == 0) find = 1; break;
- }
- }
- if(find == 1)
- {
- //在此处赋给其 方向,因为只有找到下一个节点的时候 ,才知道它的具体方向
- top++;
- st[top].i = i; st[top].j = j; st[top].di = -1; //找到则进栈
- mg[i][j] = -1; //此处设置为不可走
- }else
- {
- mg[st[top].i][st[top].j] = 0; //找不到则出栈,并且设置其为可走,虽然设置其为可走,但是却不会形成死循环,因为它的方向是递增的
- top--; //即是用 di 方向变量来 确定其下一个值
- }
- }
- printf("\n没有符合的路径\n");
- }
- void main1()
- {
- mgpath(1,1,8,8);
- }