【发布时间】:2022-01-15 13:58:48
【问题描述】:
输入 N(方阵的维度),使得 N 为 奇数,并且在区间 [1,100] 内。对于输入的矩阵,检查是否是目标矩阵:如果是,打印YES;如果没有,打印 NO。
目标矩阵是从中心开始按同心圆组织的矩阵。每个同心圆的前一个同心圆的值为 -1。例子:
我尝试通过使用while 循环来增加从中心增加开始的radius 来解决这个问题。在里面,我使用了两个for 循环来遍历该部分并检查值是否符合上面给出的规则。
我不确定这是否是一个好方法。你有什么建议吗?
#include <stdio.h>
#define DIM 100
int main() {
int matrix[DIM][DIM];
int N;
int targetMatrix = 1;
int matrixCenter;
int radius;
do{
printf("Enter N: ");
scanf("%d", &N);
if (N % 2 == 0 || N < 1 || N > 100){
printf("Invalid value of N.\n");
}
} while (N % 2 == 0 || N < 1 || N > 100);
// Matrix Entry
printf("Enter the matrix: ");
int i, j;
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
scanf("%d", &matrix[i][j]);
}
}
// Value at Center
matrixCenter = matrix[N/2][N/2];
radius = 1;
// (N - 1) / 2 is the distance from center of matrix to its side
while (radius <= (N - 1) / 2)
{
for(i = N/2 - radius; i <= N/2 + radius; i++){
for(j = N/2 - radius; j <= N/2 + radius; j++){
if (i == N/2 && j == N/2) // Center Value
continue;
if (matrix[i][j] != matrixCenter - radius)
targetMatrix = 0;
}
}
if (targetMatrix == 0){
printf("NO: This is not a target matrix"); // If not a target matrix
return 1;
}
radius++;
}
printf("YES: this is a target matrix"); // If it is a target matrix
return 0;
}
【问题讨论】:
-
这很好,但有点冗长。对于 (i=0; I
-
您正在测试太多的值:对于每个半径,您都测试了一个完整的子矩阵(除了它的中心),而不是测试第一行和最后一行以及第一列和最后一列,或者与它应该具有的理论值进行比较。
-
@PtitXav 是的,我已经意识到了。我只是不确定如何仅测试该子矩阵的“shell”值/
标签: arrays c for-loop matrix while-loop