Java 程序判断给定的矩阵是否为稀疏矩阵


本文将介绍如何判断给定的矩阵是否是稀疏矩阵。如果矩阵中的大多数元素为 0,则该矩阵称为稀疏矩阵。这意味着它包含非常少的非零元素。

下面是演示说明 −

假设我们的输入是

Input matrix:
4 0 6
0 0 9
6 0 0

所需的输出为

Yes, the matrix is a sparse matrix

算法

Step 1 - START
Step 2 - Declare an integer matrix namely input_matrix
Step 3 - Define the values.
Step 4 - Iterate over each element of the matrix using two for-loops, count the number of elements that have the value 0.
Step 5 - If the zero elements is greater than half the total elements, It’s a sparse matrix, else its not.
Step 6 - Display the result.
Step 7 - Stop

示例 1

在此,我们将所有操作绑定到“main”函数下。

public class Sparse {
   public static void main(String args[]) {
      int input_matrix[][] = {
         { 4, 0, 6 },
         { 0, 0, 9 },
         { 6, 0, 0 }
      };
      System.out.println("The matrix is defined as: ");
      int rows = 3;
      int column = 3;
      int counter = 0;
      for (int i = 0; i < rows; i++) {
         for (int j = 0; j < column; j++) {
            System.out.print(input_matrix[i][j] + " ");
         }
         System.out.println();
      }
      for (int i = 0; i < rows; ++i)
         for (int j = 0; j < column; ++j)
            if (input_matrix[i][j] == 0)
               ++counter;
            if (counter > ((rows * column) / 2))
               System.out.println("\nYes, the matrix is a sparse matrix");
            else
               System.out.println("\nNo, the matrix is not a sparse matrix");
   }
}

输出

The matrix is defined as:
4 0 6
0 0 9
6 0 0

Yes, the matrix is a sparse matrix

示例 2

在此,我们将操作封装到函数中,展示面向对象的编程。

public class Sparse {
   static int rows = 3;
   static int column = 3;
   static void is_sparse(int input_matrix[][]){
      int counter = 0;
      for (int i = 0; i < rows; i++) {
         for (int j = 0; j < column; j++) {
            System.out.print(input_matrix[i][j] + " ");
         }
         System.out.println();
      }
      for (int i = 0; i < rows; ++i)
         for (int j = 0; j < column; ++j)
            if (input_matrix[i][j] == 0)
               ++counter;
            if (counter > ((rows * column) / 2))
               System.out.println("\nYes, the matrix is a sparse matrix");
            else
               System.out.println("\nNo, the matrix is not a sparse matrix");
   }
   public static void main(String args[]) {
      int input_matrix[][] = { { 4, 0, 6 },
         { 0, 0, 9 },
         { 6, 0, 0 }
      };
      System.out.println("The matrix is defined as: ");
      is_sparse(input_matrix);
   }
}

输出

The matrix is defined as:
4 0 6
0 0 9
6 0 0

Yes, the matrix is a sparse matrix

更新日期: 2022 年 3 月 29 日

275 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.