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
抵达终点! 

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

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

相关推荐
好奇龙猫2 天前
【大学院-新的可能-新的挑战-新的机缘:生活-取在留卡说明 2】
生活
FunW1n2 天前
以捕手之心,以垂钓之意,渡生活漫漫
生活
Xp021911033 天前
知网研学、万方、WPS、大以论文四大排版工具横评,新用户免费排版等你领!
前端·css·html·生活·wps·论文排版
葡萄城技术团队3 天前
观察生活:人是如何分词的
算法·生活
吃好睡好便好3 天前
詹姆斯·艾伦语录
学习·生活
吃好睡好便好4 天前
说说免疫力的维护
学习·生活
我一拳打弯你A柱4 天前
第八章:数据中台
生活·小说
USC-XiangLuXun4 天前
局部科技小创新是有意义的
科技·学习·生活
李迟4 天前
2026年5月个人工作生活总结
生活
普贤莲花4 天前
【【2026年第22周---写于20260531】---好好工作,好好生活】
程序人生·算法·leetcode·生活