7-2 Determine the upper triangular matrix fraction 20

An upper triangular matrix refers to a matrix in which all elements below the main diagonal are 0; the main diagonal is the line connecting the upper left corner to the lower right corner of the matrix.

This question requires writing a program to determine whether a given square matrix is ​​an upper triangular matrix.

Input format:

The first line of input gives a positive integer T, which is the number of matrices to be tested. Next, the information of T matrices is given: the first line of each matrix information gives a positive integer n not exceeding 10. Then there are n lines, each line giving n integers separated by spaces.

Output format:

The judgment result of each matrix occupies one row. If the input matrix is ​​an upper triangular matrix, output "YES", otherwise output "NO".

Input example:

3
3
1 2 3
0 4 5
0 0 6
2
1 0
-8 2
3
1 2 3
1 4 5
0 -1 6

Output sample:

YES
NO
NO

Thanks to Yu Chunqiao of the Mechanical and Electrical Installation Branch of the Seventh China Water Bureau for supplementing the data!

Code length limit

16 KB

time limit

400 ms

memory limit

64 MB

#include <stdio.h>

int isUpperTriangular(int matrix[10][10], int n) {
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (matrix[i][j] != 0) {
                return 0; // 不是上三角矩阵,返回0
            }
        }
    }
    return 1; // 是上三角矩阵,返回1
}

int main() {
    int T;
    scanf("%d", &T);

    while (T--) {
        int n;
        scanf("%d", &n);

        int matrix[10][10];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                scanf("%d", &matrix[i][j]);
            }
        }

        if (isUpperTriangular(matrix, n)) {
            printf("YES\n");
        } else {
            printf("NO\n");
        }
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/Androidandios/article/details/134540066