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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP