编写一个Java程序来查找稀疏矩阵,并附带一个示例。任何矩阵如果包含大量零,就被称为稀疏矩阵。查找稀疏矩阵的数学公式是:零的总数 >= (行数 * 列数)/2。
在这个稀疏矩阵的例子中,我们声明了一个3*3的sp_arr整型矩阵。接下来,我们使用for循环来迭代矩阵。我们在for循环中使用If语句来检查零。根据结果,我们进行累加。然后,我们使用If Else语句来检查零的总数是否大于(行数 * 列数)/2。根据结果,Java代码会打印输出。
public class SparseMatrix {
public static void main(String[] args) {
int i, j, total = 0;
int[][] sp_arr = {{0, 0, 0}, {0, 1, 0}, {5, 4, 9}, {3, 0, 0}};
int rows = sp_arr.length;
int columns = sp_arr[0].length;
for(i = 0; i < rows ; i++) {
for(j = 0; j < columns; j++){
if(sp_arr[i][j] == 0) {
total++;
}
}
}
if(total > ((rows * columns)/2)) {
System.out.println("\nMatrix is a Sparse Matrix");
}
else {
System.out.println("\nMatrix is Not a Sparse Matrix");
}
}
}

这个稀疏矩阵的示例代码与上面的相同。这里,我们手动添加了行大小和列大小。我们还对数组做了一些更改,并在第一行和第二列添加了9。
public class SparseMatrix {
public static void main(String[] args) {
int i, j, total = 0;
int[][] sp_arr = {{0, 9, 0}, {0, 1, 0}, {5, 4, 9}, {3, 0, 0}};
for(i = 0; i < 4 ; i++) {
for(j = 0; j < 3; j++){
if(sp_arr[i][j] == 0) {
total++;
}
}
}
if(total > ((4 * 3)/2)) {
System.out.println("\nIt is a Sparse Matrix");
}
else {
System.out.println("\nIt is Not a Sparse Matrix");
}
}
}
It is Not a Sparse Matrix
Java程序查找矩阵是否为稀疏矩阵 示例2
这个Java代码与上面的相同。然而,这个稀疏代码允许用户输入行数、列数和矩阵元素。
import java.util.Scanner;
public class SparseMatrix {
private static Scanner sc;
public static void main(String[] args) {
int i, j, rows, columns, total = 0;
sc= new Scanner(System.in);
System.out.println("\n Enter Rows and Columns : ");
rows = sc.nextInt();
columns = sc.nextInt();
int[][] arr = new int[rows][columns];
System.out.println("\n Please Enter the Sparse Matrix Items : ");
for(i = 0; i < rows; i++) {
for(j = 0; j < columns; j++) {
arr[i][j] = sc.nextInt();
}
}
for(i = 0; i < rows ; i++)
{
for(j = 0; j < columns; j++)
{
if(arr[i][j] == 0) {
total++;
}
}
}
if(total > ((rows * columns)/2)) {
System.out.println("\nIt is a Sparse Matrix");
}
else {
System.out.println("\nIt is Not a Sparse Matrix");
}
}
}
稀疏矩阵输出
Enter Rows and Columns :
3 3
Please Enter the Sparse Matrix Items :
10 20 0
0 0 0
90 0 0
It is a Sparse Matrix
我用较少的零来试试。
Enter Rows and Columns :
3 3
Please Enter the Sparse Matrix Items :
1 2 3
0 0 0
5 0 9
It is Not a Sparse Matrix