题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

#include<stdio.h>
#include<malloc.h>
int main()
{
    int raw, col;
    scanf("%d%d", &raw, &col);
    int x = 0, y = 0;
    int** maze = malloc(sizeof(int*) * raw);
    for (int i = 0; i < raw; i++)
    {
        maze[i] = malloc(sizeof(int) * col);
        for (int j = 0; j < col; j++)
            scanf("%d", &maze[i][j]);//输入矩阵
    }
    maze[0][0] = 2;
  //从上往下倒水,并标记走过的路
    while (x != raw - 1 || y != col - 1)
    {
        if (x != raw - 1 && maze[x + 1][y] == 0)
        {
            maze[x + 1][y] = 2;
            x++;
        }
        else if (y != col - 1 && maze[x][y + 1] == 0)
        {
            maze[x][y + 1] = 2;
            y++;
        }
        else if (y != 0 && maze[x][y - 1] == 0)
        {
            maze[x][y - 1] = 2;
            y--;
        }
        else if (x != 0 && maze[x - 1][y] == 0)
        {
            maze[x - 1][y] = 2;
            x--;
        }
	  //没路走,水开始回流,并封路。
        else if (x != 0 && maze[x - 1][y] == 2)
        {
            maze[x][y] = 1;
            x--;
        }
        else if (y != 0 && maze[x][y - 1] == 2)
        {
            maze[x][y] = 1;
            y--;
        }
        else if (y != col - 1 && maze[x][y - 1] == 2)
        {
            maze[x][y] = 1;
            y++;
        }
        else if (x != raw - 1 && maze[x - 1][y] == 2)
        {
            maze[x][y] = 1;
            x++;
        }
    }
    x = 0, y = 0;
  //开始通过标记过的路再走一遍,并输出。
    while (x != raw - 1 || y != col - 1)
    {
        printf("(%d,%d)\n", x, y);
        if (x != raw - 1 && maze[x + 1][y] == 2)
        {
            maze[x + 1][y] = 1;
            x++;
        }
        else if (y != col - 1 && maze[x][y + 1] == 2)
        {
            maze[x][y + 1] = 1;
            y++;
        }
        else if (y != 0 && maze[x][y - 1] == 2)
        {
            maze[x][y - 1] = 1;
            y--;
        }
        else if (x != 0 && maze[x - 1][y] == 2)
        {
            maze[x - 1][y] = 1;
            x--;
        }
    }
    printf("(%d,%d)", x, y);
    return 0;
}

全部评论

相关推荐

Wy_m:只要不是能叫的上名的公司 去实习没有任何意义 不如好好沉淀自己
点赞 评论 收藏
分享
Beeee0927:正确的建议
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务