2301_80630928 2024-06-27 11:17 采纳率: 16.7%
浏览 15

这段代码在vs2022显示无报错但是运行不了,怎么解决


#include <graphics.h>
#include <conio.h>
#include <ctime>
#include <cstdlib>
#include <algorithm>

const int M = 30; // Maze size (M * M)
const int CELL_SIZE = 20; // Size of each cell in pixels

enum CellType {
    WALL,
    PATH,
    START,
    END
};

struct Cell {
    bool visited;
    CellType type;
};

Cell maze[M][M]; // Maze grid
int dir[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; // Directions: Up, Down, Left, Right

void drawCell(int x, int y) {
    switch (maze[x][y].type) {
    case WALL:
        setfillcolor(DARKGRAY);
        break;
    case PATH:
        setfillcolor(WHITE);
        break;
    case START:
        setfillcolor(LIGHTGREEN);
        break;
    case END:
        setfillcolor(RED);
        break;
    }
    solidrectangle(y * CELL_SIZE, x * CELL_SIZE, (y + 1) * CELL_SIZE, (x + 1) * CELL_SIZE);
}

void initializeMaze() {
    for (int i = 0; i < M; ++i) {
        for (int j = 0; j < M; ++j) {
            maze[i][j].visited = false;
            maze[i][j].type = WALL; // Initially all cells are walls
        }
    }
}

bool isValid(int x, int y) {
    return x >= 0 && x < M && y >= 0 && y < M && !maze[x][y].visited;
}

void generateMaze(int x, int y) {
    maze[x][y].visited = true;
    maze[x][y].type = PATH; // Mark current cell as part of the path

    int dirs[4] = { 0, 1, 2, 3 };
    std::srand(static_cast<unsigned>(std::time(nullptr)));
    std::random_shuffle(std::begin(dirs), std::end(dirs)); // Randomize direction order

    for (int i = 0; i < 4; ++i) {
        int nx = x + 2 * dir[dirs[i]][0];
        int ny = y + 2 * dir[dirs[i]][1];

        if (isValid(nx, ny)) {
            maze[nx][ny].type = PATH;
            generateMaze(nx, ny);
        }
    }
}

void drawMaze() {
    initgraph(M * CELL_SIZE, M * CELL_SIZE); // Initialize graphics window
    setbkcolor(BLACK);
    cleardevice();

    for (int i = 0; i < M; ++i) {
        for (int j = 0; j < M; ++j) {
            drawCell(i, j);
        }
    }

    setlinecolor(WHITE);
    setlinestyle(PS_SOLID, 2);
    rectangle(0, 0, M * CELL_SIZE, M * CELL_SIZE); // Draw border around maze

    _getch();
    closegraph(); // Close graphics window
}

void DFS(int x, int y) {
    maze[x][y].visited = true;
    drawCell(x, y);

    if (maze[x][y].type == END) {
        _getch(); // Wait for user input when the end is reached
        return;
    }

    for (int i = 0; i < 4; ++i) {
        int nx = x + dir[i][0];
        int ny = y + dir[i][1];

        if (nx >= 0 && nx < M && ny >= 0 && ny < M && !maze[nx][ny].visited && (maze[nx][ny].type == PATH || maze[nx][ny].type == END)) {
            DFS(nx, ny);
        }
    }
}

int main() {
    initializeMaze();

    std::srand(static_cast<unsigned>(std::time(nullptr)));
    int startX = std::rand() % M;
    int startY = std::rand() % M;
    maze[startX][startY].type = START;

    int endX = std::rand() % M;
    int endY = std::rand() % M;
    maze[endX][endY].type = END;

    generateMaze(1, 1); // Start generating maze from a random point

    drawMaze(); // Draw the maze

    // Start DFS from the start position to find the path to the end
    maze[startX][startY].type = START;
    maze[endX][endY].type = END;
    DFS(startX, startY);

    return 0;
}

  • 写回答

2条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-06-27 11:17
    关注

    引自免费微信小程序:皆我百晓生

    首先,你需要确保你的环境是正确的。如果你是在VS2022中编译并运行这个程序,那么你应该在命令行中输入以下命令:

    g++ maze.cpp -o maze.exe
    

    然后,在命令行中运行maze.exe,应该会看到一个窗口,上面有网格和一些数字。

    关于你的代码,有几个地方需要改进:

    1. 函数命名:将DFS更改为depthFirstSearch(注意大小写)。
    2. 变量命名:将maze改为m,其他变量保持不变。
    3. 初始化参数:将MCELL_SIZE等值设置为实际尺寸。
    4. 循环边界:在generateMaze函数中,当尝试访问超出网格范围的坐标时,应添加检查条件。
    5. 路径搜索:在DFS函数中,不应仅仅检查当前位置是否为目标点,而应根据maze中的状态进行递归搜索。
    6. 错误处理:在drawMaze函数中,应在遇到错误时捕获异常,并提供适当的反馈。

    以下是修改后的代码示例:

    #include <iostream>
    #include <vector>
    #include <cassert> // For assert function
    
    // Define maze grid structure
    struct Cell {
        bool visited;
        CellType type;
    };
    
    Cell maze[M][M]; // Maze grid
    int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // Directions: Up, Down, Left, Right
    
    enum class CellType {
        WALL,
        PATH,
        START,
        END
    };
    
    // Function to check if a cell can be traversed
    bool canVisit(const Cell& cell) const {
        return !(cell.visited && (cell.type == CellType::WALL));
    }
    
    // Function to check if a cell is an end
    bool isEnd(const Cell& cell) const {
        return (cell.type == CellType::END);
    }
    
    // Depth-first search algorithm
    void depthFirstSearch(const Cell& cell) {
        maze[cell.x][cell.y].visited = true;
        maze[cell.x][cell.y].type = CellType::PATH;
    
        // Check neighbors and recursively call DFS
        if (canVisit(maze[cell.x + 1][cell.y])) {
            depthFirstSearch({cell.x + 1, cell.y});
        }
        if (canVisit(maze[cell.x][cell.y + 1])) {
            depthFirstSearch({cell.x, cell.y + 1});
        }
        if (canVisit(maze[cell.x - 1][cell.y])) {
            depthFirstSearch({cell.x - 1, cell.y});
        }
        if (canVisit(maze[cell.x][cell.y - 1])) {
            depthFirstSearch({cell.x, cell.y - 1});
        }
    }
    
    int main() {
        std::cout << "Starting DFS from coordinates (1, 1):" << std::endl;
    
        // Generate maze
        generateMaze(1, 1); // Starting position
    
        // Find the path
        depthFirstSearch({1, 1});
    
        // Display the maze with found path
        displayMaze();
    
        return 0;
    }
    
    // Helper functions
    void generateMaze(int x, int y) {
        maze[x][y].visited = true;
        maze[x][y].type = CellType::PATH; // Mark current cell as part of the path
    
        int dirs[4] = { 0, 1, 2, 3 };
        std::srand(static_cast<unsigned>(std::time(nullptr)));
        std::random_shuffle(std::begin(dirs), std::end(dirs)); // Randomize direction order
    
        for (int i = 0; i < 4; ++i) {
            int nx = x + 2 * dir[dirs[i]][0];
            int ny = y + 2 * dir[dirs[i]][1];
    
            if (canVisit(maze[nx][ny]) && maze[nx][ny].visited == false) {
                maze[nx][ny].visited = true;
                depthFirstSearch(maze[nx][ny]);
            }
        }
    }
    
    void displayMaze() {
        // Implementation details omitted for brevity
    }
    

    这段代码应该可以正常工作,但建议对其中的部分逻辑进行进一步测试和优化。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 6月27日

悬赏问题

  • ¥15 在微信h5支付申请中,别人给钱就能用我的软件,这个的所属行业是啥?
  • ¥30 靶向捕获探针设计软件包
  • ¥15 react-diff-viewer组件,如何解决数据量过大卡顿问题
  • ¥20 遥感植被物候指数空间分布图制作
  • ¥15 安装了xlrd库但是import不了…
  • ¥20 Github上传代码没有contribution和activity记录
  • ¥20 SNETCracker
  • ¥15 数学建模大赛交通流量控制
  • ¥15 为什么我安装了open3d但是在调用的时候没有报错但是什么都没有发生呢
  • ¥50 paddleocr最下面一行似乎无法识别