📜  判断给定矩阵是否为下三角矩阵的Java程序

📅  最后修改于: 2022-05-13 01:54:20.155000             🧑  作者: Mango

判断给定矩阵是否为下三角矩阵的Java程序

在下三角矩阵中,存在于对角线上方的元素应为 0。给定一个矩阵,任务是检查矩阵是否为下三角形式。矩阵必须是方阵。如果主对角线以上的所有项都为零,则方阵称为下三角矩阵。

例子 -

Input:
    1    0    0
    1    2    0
    1    2    3
    
Output: Matrix is lower triangular matrix

Input:
    1    2    2
    2    1    1
    2    2    2
    
Output: Matrix is not a lower triangular matrix

方法:

  1. 检查给定矩阵是否为方阵。
  2. 如果是,则遍历上三角部分矩阵。
  3. 检查主对角线上的所有条目是否为零。
  4. 如果是,则 print Matrix 是下三角矩阵。

下面是上述方法的实现:

Java
// Java Program to check for
// a lower triangular matrix.
  
import java.util.Scanner;
  
public class LowerTriangularMatrix {
    public static boolean
    isLowerTriangularMatrix(int[][] matrix)
    {
        for (int i = 0; i < matrix[0].length; i++) {
            for (int j = i + 1; j < matrix[0].length; j++) {
                if (matrix[i][j] != 0)
                    return false;
            }
        }
        return true;
    }
    public static void main(String args[])
    {
        int rows = 3, columns = 3;
  
        // returns true if number of rows and columns are
        // equal else false
        if (rows == columns) {
            // initializing the matrix
            int Matrix[][]
                = { { 1, 0, 0 }, { 2, 3, 0 }, { 5, 6, 7 } };
  
            // Display the values of matrix
            System.out.println("Matrix is : ");
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++) {
                    System.out.print(Matrix[i][j] + "\t");
                }
                System.out.println();
            }
  
            // Function call
            boolean result
                = isLowerTriangularMatrix(Matrix);
  
            // returns true if matrix is lower triangular
            // matrix else false
            if (result == true) {
                System.out.println(
                    "Matrix is lower triangular matrix");
            }
            else {
                System.out.println(
                    "Matrix is not lower triangular matrix");
            }
        }
        else {
            System.out.println(
                "Number of rows and number of columns should be equal");
        }
    }
}


输出
Matrix is : 
1    0    0    
2    3    0    
5    6    7    
Matrix is lower triangular matrix

时间复杂度: O(N 2 ),其中 N 是方阵中行的长度。