You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

2D向量构建迷宫时竖墙(|)位置错误问题排查

迷宫竖墙位置错误修复

问题描述

我尝试实现一个由用户输入宽高生成的全封闭迷宫打印功能,但打印迷宫时竖墙(|)的位置不正确。竖墙的数量正确,但位置有误。

错误代码

int vectorLength = (userRows * 2) + 1;
int vectorWidth = (userColloms * 4) + 1;

std::vector<std::vector<std::string>> maze(vectorWidth, std::vector<std::string>(vectorLength, ""));

for (unsigned int i = 0; i < vectorLength; i++) {
    int testj = 0;
    for (unsigned int j = 0; j < vectorWidth; j++) {
        if (i % 2 == 0){
            if (j % 4 == 0) {
                maze.at(j).at(i) = "+";
            } else {
                maze.at(j).at(i) = "-";
            }
        }
        if (i % 2 != 0){
            if (j % 4 == 0) {
                maze.at(j).at(i) = "|";
            }
        }
    }
}

错误输出(输入3 3时)

+---+---+---+
||||
+---+---+---+
||||
+---+---+---+
||||
+---+---+---+
Program ended with exit code: 0

问题原因与修复方案

核心问题

  1. 二维容器初始化顺序错误:把vectorWidth(列数)作为外层容器大小,vectorLength(行数)作为内层容器大小,导致迷宫行列颠倒。
  2. 元素访问索引颠倒:使用maze.at(j).at(i)先访问列再访问行,不符合行优先遍历逻辑,直接导致竖墙位置错乱。
  3. 奇数行未填充空白:奇数行非竖墙位置是空字符串,打印时被忽略,导致竖墙挤在一起。

修改后的代码

int userRows = 3;
int userColloms = 3;

int vectorLength = (userRows * 2) + 1;
int vectorWidth = (userColloms * 4) + 1;

// 修正初始化顺序:行在前列在后,初始值设为空格
std::vector<std::vector<std::string>> maze(vectorLength, std::vector<std::string>(vectorWidth, " "));

for (unsigned int i = 0; i < vectorLength; i++) {
    for (unsigned int j = 0; j < vectorWidth; j++) {
        if (i % 2 == 0) {
            // 处理水平线行
            if (j % 4 == 0) {
                maze.at(i).at(j) = "+";
            } else {
                maze.at(i).at(j) = "-";
            }
        } else {
            // 处理竖墙行
            if (j % 4 == 0) {
                maze.at(i).at(j) = "|";
            }
            // 其他位置保持初始空格,无需额外赋值
        }
    }
}

// 打印迷宫
for (const auto& row : maze) {
    for (const auto& c : row) {
        std::cout << c;
    }
    std::cout << std::endl;
}

正确输出(输入3 3时)

+---+---+---+
|   |   |   |
+---+---+---+
|   |   |   |
+---+---+---+
|   |   |   |
+---+---+---+

内容的提问来源于stack exchange,提问作者MiningCode20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:45:59