原始问题:
C++编程:小红获一矩阵,格色红绿蓝,Q次询子矩阵色种数
以下是使用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 colorCount = 0; // 颜色种类数
for (int i = startRow; i <= endRow; i++) {
for (int j = startCol; j <= endCol; j++) {
int color = matrix[i][j];
colors[color - 1] = 1; // 将对应颜色的计数置为1
}
}
for (int i = 0; i < 3; i++) {
colorCount += colors[i]; // 统计颜色种类数
}
return colorCount;
}
int main() {
int matrix[MAX_SIZE][MAX_SIZE];
int n, m; // 矩阵的行数和列数
int q; // 询问次数
printf("请输入矩阵的行数和列数:");
scanf("%d %d", &n, &m);
printf("请输入矩阵的元素(红色:1,绿色:2,蓝色:3):
");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("请输入询问次数:");
scanf("%d", &q);
for (int i = 0; i < q; i++) {
int startRow, endRow, startCol, endCol;
printf("请输入第%d次询问的子矩阵的左上角和右下角坐标:", i + 1);
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;
}这段代码首先会读取矩阵的行数和列数,然后读取矩阵的元素(红色:1,绿色:2,蓝色:3)。接下来会读取询问次数,并依次读取每次询问的子矩阵的左上角和右下角坐标。最后,通过调用countColors函数计算子矩阵的颜色种类数,并输出结果。
注意:为了简化代码,这里假设输入的矩阵大小不超过100x100。如果需要处理更大的矩阵,请根据实际情况修改MAX_SIZE的值。
Prev:"C++代码:统计矩阵子区域的颜色种类数"