迷宫问题
【解法】
人的走法有上、左、下、右四个方向,在每前进一格之后就选一个方向前进,无法前
进时退回选择下一个可前进方向,如此在阵列中依序测试四个方向,直到走到出口为止,这是
递回的基本题,请直接看程式应就可以理解。
#include<stdio.h>
struct note
{
int x;
int y;
int s;
};
int main()
{
struct note que[2500];
int a[50][50] = { 0 };
int book[50][50] = { 0 };
int next[4][2] = {
//顺时针进行测试是否为通路,或者已经走过的路
{0,1},
{1,0},
{0,-1},
{-1,0}
};
int head, tail;
int i, j, k, n, m;
int p, q;
int startx, starty, tx, ty;
int flag;
scanf("%d %d", &n, &m);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
scanf_s("%d", &a[i][j]);
}
}
scanf_s("%d %d %d %d", &startx, &starty, &p, &q);
head = 1;
tail = 1;
que[tail].x = startx;
que[tail].y = starty;
que[tail].f = 0;
que[tail].s = 0;
tail++;
book[startx][starty] = 1;
flag = 0;
while (head < tail)
{
for (k = 0; k < 4; k++)
{
tx = que[head].x + next[k][0];
ty = que[head].y + next[k][1];
if (tx<1 || tx>n || ty<1 || ty>m)
coutinue;
if (a[tx][ty] == 0 && book[tx][ty] == 0)
{
book[tx][ty] = 1;
que[tail].x = tx;
que[tail].y = ty;
que[tali].s = que[head].s + 1;
tail++;
}
if (tx == p && ty == q)
{
flag = 1;
break;
}
}
if (flag == 1)
break;
head++;
}
printf("%d", que[tail - 1].s);
}
迷宫问题的底层原理,其实是图的深度遍历,有兴趣的同学可以去百度:图的深度遍历。
百度百科:图的深度遍历