aiaiask.com©

开花即结果 提问即答案

"C++代码:统计矩阵子区域的颜色种类数"
原始问题:

"C++代码:统计矩阵子区域的颜色种类数"

以下是使用C语言编写的代码,用于计算子矩阵的颜色种类数:

#include <stdio.h>

#define MAX_SIZE 100

int countColors(int matrix[MAX_SIZE][MAX_SIZE], int startRow, int endRow, int startCol, int endCol) {
    int colors[3] = {0}; // 用于记录红、绿、蓝三种颜色的数量
    int i, j, count = 0;

    for (i = startRow; i <= endRow; i++) {
        for (j = startCol; j <= endCol; j++) {
            int color = matrix[i][j];
            colors[color - 1] = 1; // 将对应颜色的标记位置为1
        }
    }

    for (i = 0; i < 3; i++) {
        count += colors[i]; // 统计颜色种类数
    }

    return count;
}

int main() {
    int matrix[MAX_SIZE][MAX_SIZE];
    int n, m, q, i, j;

    printf("请输入矩阵的行数和列数(以空格分隔):");
    scanf("%d %d", &n, &m);

    printf("请输入矩阵的元素(红色:1,绿色:2,蓝色:3):  
");
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    printf("请输入询问次数:");
    scanf("%d", &q);

    printf("请输入每次询问的子矩阵的左上角和右下角坐标(以空格分隔):  
");
    for (i = 0; i < q; i++) {
        int startRow, endRow, startCol, endCol;
        scanf("%d %d %d %d", &startRow, &startCol, &endRow, &endCol);
        int colorCount = countColors(matrix, startRow, endRow, startCol, endCol);
        printf("第%d次询问的子矩阵颜色种类数为:%d  
", i + 1, colorCount);
    }

    return 0;
}

这段代码首先会读取矩阵的行数和列数,然后读取矩阵的元素,接着读取询问次数和每次询问的子矩阵的左上角和右下角坐标。最后,通过调用countColors函数计算子矩阵的颜色种类数,并输出结果。

注意:这段代码假设输入的矩阵元素只能是1、2、3,分别代表红色、绿色和蓝色。如果需要支持其他颜色,可以根据实际情况进行修改。

"C++代码:统计矩阵子区域的颜色种类数"
https://www.aiaiask.com/ask/45364.html
AI / 模型Siliconflow
时间 / DATEAugust 27, 2023, 10:58 AM
语言zh-CN
IP / 区域四川 成都