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

C语言实现扫雷矩阵:放置炸弹及计算相邻炸弹数量的开发问题

扫雷游戏代码完善方案

原代码已知问题

  • 二维数组matrix未分配内存,直接访问会触发段错误
  • 存在拼写错误:rows*colums应为rows*columns,printf("Error);缺少字符串闭合引号
  • 错误校验后未终止程序,非法输入下仍会执行后续逻辑
  • 未初始化随机数种子,每次运行生成的随机值固定
  • 矩阵赋值逻辑不符合需求,未按指定数量放置炸弹,也未统计相邻炸弹总数

核心功能实现思路

  • 约定规则:矩阵中用-1表示炸弹,其余数值表示当前单元格周围8个相邻位置的炸弹总数
  1. 内存初始化:先为二维矩阵分配对应行列数的内存空间,所有单元格初始值设为0
  2. 放置指定数量炸弹:循环生成随机行列坐标,若对应位置未放置炸弹则赋值为-1,直到放够输入的炸弹数量
  3. 统计相邻炸弹数:遍历每个非炸弹单元格,检查其上下左右、四个对角线共8个方向的相邻单元格,每遇到一个炸弹则当前单元格数值+1(注意边界判断,避免越界访问)
  4. 输出优化:打印矩阵时炸弹用*表示,更符合扫雷的直观展示

修正后完整代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// 约定-1代表炸弹
#define BOMB -1

int main(){
    int rows, columns, i, j, bombs, **matrix;
    // 8个相邻方向的偏移量
    int dirs[8][2] = {{-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,1}, {1,-1}, {1,0}, {1,1}};

    // 初始化随机数种子
    srand((unsigned int)time(NULL));

    printf("Enter the rows: ");
    scanf("%d", &rows);
    printf("Enter the columns: ");
    scanf("%d", &columns);
    printf("Enter the bombs: ");
    scanf("%d", &bombs);

    // 非法输入校验
    if (bombs >= rows * columns || bombs <= 0) {
        printf("Error: 炸弹数量非法\n");
        return 1;
    }

    // 分配二维矩阵内存
    matrix = (int **)malloc(sizeof(int *) * rows);
    for (i = 0; i < rows; i++) {
        matrix[i] = (int *)malloc(sizeof(int) * columns);
        // 初始化所有单元格为0
        for (j = 0; j < columns; j++) {
            matrix[i][j] = 0;
        }
    }

    // 放置指定数量的炸弹
    int placed = 0;
    while (placed < bombs) {
        int r = rand() % rows;
        int c = rand() % columns;
        if (matrix[r][c] != BOMB) {
            matrix[r][c] = BOMB;
            placed++;
        }
    }

    // 统计每个单元格相邻的炸弹数量
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            // 跳过炸弹单元格
            if (matrix[i][j] == BOMB) continue;
            int count = 0;
            // 遍历8个方向
            for (int d = 0; d < 8; d++) {
                int nr = i + dirs[d][0];
                int nc = j + dirs[d][1];
                // 边界判断,避免越界
                if (nr >= 0 && nr < rows && nc >=0 && nc < columns) {
                    if (matrix[nr][nc] == BOMB) count++;
                }
            }
            matrix[i][j] = count;
        }
    }

    // 输出扫雷地图
    printf("\n扫雷地图如下:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            if (matrix[i][j] == BOMB) {
                printf("%2c", '*');
            } else {
                printf("%2d", matrix[i][j]);
            }
        }
        printf("\n\n");
    }

    // 释放内存避免泄漏
    for (i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:15:02