C++解决生活中的算法:走迷宫

一、问题

给出一个矩阵(表示迷宫),由n行m列组成,每个元素只能是0或者1,0表示死路,1表示通路,求出一条从左上角走到右下角的可能的路线,并输出其长度。

例如:

已知迷宫图1,可以行走的路线为图2。

图1 图2

二、实现

首先,我们先将框架搭建好。

cpp 复制代码
#include <iostream>
using namespace std;

int n, m;
int maze[105][105];

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cin >> maze[i][j];
        }
    }
    printMinLength(n, m, maze);
    return 0;
}

然后,我们拼接出函数。

cpp 复制代码
#include <iostream>
using namespace std;

int n, m;
int maze[105][105];

bool isRoad(int x, int y); // 是不是通路
bool go(int &x, int &y); // 向前试探1步
void printMinLength(int n, int m, int maze[][105]); // 输出最短路径长度

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cin >> maze[i][j];
        }
    }
    printMinLength(n, m, maze);
    return 0;
}

bool isRoad(int x, int y)
{
    // 情况1: 越界
    if (x < 1 || y < 1) return false;
    if (x > n || y > m) return false;

    // 情况2: 在矩阵内死路
    if (maze[x][y] == 0) return false;

    // 情况3: 在矩阵内通路
    return true;
}

bool go(int &x, int &y)
{
    if (isRoad(x + 1, y)) // 向下走是通路
    {
        x++;
        return true;
    }
    else if (isRoad(x, y + 1)) // 向右走是通路
    {
        y++;
        return true;
    }
    else if (isRoad(x - 1, y)) // 向上是通路
    {
        x--; // 回溯到上一步
        return true;
    }
    else if (isRoad(x, y - 1)) // 向左是通路
    {
        y--;
        return true;
    }
    else
    {
        return false; // 四个方向都不通,迷宫无解
    }
}

void printMinLength(int n, int m, int maze[][105])
{
    int x = 1, y = 1;
    while (true)
    {
        cout << x << "," << y << " -> ";
        if (!go(x, y))
        {
            cout << "迷宫无解" << endl;
            break;
        }
        if (x == n && y == m)
        {
            cout << n << "," << m << endl << "抵达终点! ";
            break;
        }
    }
}

最后,我们来运行一下。

python 复制代码
INPUT
5 5
1 1 1 1 1
0 0 0 0 1
0 1 0 0 1
0 1 0 1 1
0 1 0 0 1

CORRECT OUTPUT
1,1 -> 1,2 -> 1,3 -> 1,4 -> 1,5 -> 2,5 -> 3,5 -> 4,5 -> 5,5
抵达终点! 

MY OUTPUT
1,1 -> 1,2 -> 1,3 -> 1,4 -> 1,5 -> 2,5 -> 3,5 -> 4,5 -> 5,5
抵达终点! 

但是无解的时候,就会开始反复横跳......

不过,只要不是无解,这个程序就可以啦!

相关推荐
财经科技9 天前
布瑞琳BRANEW:高端洗护领航者,铸就品质生活新典范
生活
理***所10 天前
湖北理元理律师事务所:科学债务优化模型的法律实践
生活
理***所10 天前
湖北理元理律师事务所:债务管理的双轨服务模式探索
生活
理***所10 天前
湖北理元理律师事务所:法律框架下的债务优化与生活重建双轨支持
生活
脑极体11 天前
鸿蒙星闪,智能生活交响乐的指挥家
华为·生活·harmonyos
明似水11 天前
点点(小红书AI搜索):生活场景的智能搜索助手
人工智能·生活
AndrewHZ11 天前
【Python与生活】如何实现一个条形码检测算法?
人工智能·pytorch·python·深度学习·算法·生活
非凡ghost12 天前
墨记APP:水墨风记事,书写生活诗意
android·智能手机·生活·软件需求
weixin_4462608512 天前
老凤祥的AI智能眼镜:让智慧更近生活
人工智能·生活
好奇龙猫13 天前
日本生活:日语语言学校-日语作文-沟通无国界(4)-题目:喜欢读书
生活