数据结构9.迷宫问题—用数组解决

迷宫有一个入口,一个出口。一个人从入口走进迷宫,目标是找到出口。阴影部分和迷宫的外框为墙,每一步走一格,每格有四个可走的方向,探索顺序为地图方向:南(下)、东(右)、北(上)、西(左)。
在这里插入图片描述

#include <stdio.h>

typedef struct
{
    int x, y;
} pos;

pos stack[200];
int top = 0;

char map[102][102] = {0};

void push(char a, char b)
{
    stack[top].x = a;
    stack[top].y = b;
    top++;
    map[a][b] = 2;
}

int main()
{

    int m, n, i, j;
    scanf("%d%d", &m, &n);
    for (i = 0; i <= m + 1; i++)
    {
        for (j = 0; j <= n + 1; j++)
        {
            if (i * j > 0 && i <= m && j <= n)
                scanf("%d", &map[i][j]);
            else
                map[i][j] = 2;
        }
    }

    if (map[1][1] == 1)
    {
        printf("There is no solution!\n");
        return 0;
    }

    push(1, 1);

    while (1)
    {
        if (top == 0)
        {
            printf("There is no solution!\n");
            return 0;
        }

        i = stack[top - 1].x;
        j = stack[top - 1].y;

        // printf("%d %d %d\n", top, i, j);

        if (i == m && j == n)
        {
            break;
        }

        if (map[i + 1][j] == 0)
        {
            push(i + 1, j);
        }

        else if (map[i][j + 1] == 0)
        {
            push(i, j + 1);
        }

        else if (map[i - 1][j] == 0)
        {
            push(i - 1, j);
        }

        else if (map[i][j - 1] == 0)
        {
            push(i, j - 1);
        }

        else
        {
            top--;
        }
    }
    for (i = 0; i < top; i++)
    {
        printf("<%d,%d> ", stack[i].x, stack[i].y);
    }
    printf("\n");
    return 0;
}
发布了58 篇原创文章 · 获赞 117 · 访问量 6816

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/103710086