我正在尝试执行从用户输入的代码,首先将这些元素转换为传统矩阵,然后将其转换为稀疏矩阵
import java.util.*;
public class SparseMatrix {
static void enterMatrix(int matrix[][], Scanner sc) {
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[0].length; ++j) {
matrix[i][j] = sc.nextInt();
}
}
}
static void displayMatrix(int[][] mat) {
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
System.out.print("\t" + mat[i][j]);
}
System.out.println();
}
}
static int checkSparseMatrix(int[][] mat) {
int cnt = 0;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
if (mat[i][j] != 0)
cnt++;
}
}
return (cnt);
}
static void sparseMatrixDisplay(int[][] mat, int cnt) {
int Spmatrix[][] = new int[cnt][3];
int a, b, c;
int k = 0;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
if (mat[i][j] != 0) {
a = i;
b = j;
c = mat[i][j];
Spmatrix[k][0] = a;
Spmatrix[k][1] = b;
Spmatrix[k][2] = c;
k++;
}
}
}
System.out.println("\nElements of Sparse matrix are :");
for (int i = 0; i < Spmatrix.length; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
System.out.print("\t" + Spmatrix[i][j]);
}
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int choice;
System.out.println("Enter the rows and columns of matrix:");
int row = sc.nextInt();
int col = sc.nextInt();
int mat[][] = new int[row][col];
do {
System.out.println("\n1. Enter Matrix");
System.out.println("2. Display Matrix");
System.out.println("3. Display Sparse matrix");
System.out.println("4. Exit");
System.out.println("Enter your choice :");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1:
System.out.println("Enter the matrix elements:");
enterMatrix(mat, sc);
break;
case 2:
System.out.println("The Entered Matrix is:");
displayMatrix(mat);
break;
case 3:
int cnt = checkSparseMatrix(mat);
System.out.println("The count is " + cnt);
if (cnt < ((row * col) / 2)) {
System.out.println("The entered matrix is a sparse matrix ");
sparseMatrixDisplay(mat, cnt);
} else
System.out.println("The entered matrix is not a sparse matrix ");
break;
case 4:
System.out.println("Exiting the Menu.....");
break;
default:
System.out.println("Enter the correct choice");
break;
}
} while (choice != 4);
sc.close();
}
}
但是我在循环中面临问题,其中矩阵在嵌套 for 循环中转换为稀疏矩阵。运行程序后,它确实执行循环,但不显示稀疏矩阵,你能帮我吗?
在我的情况下,正如我在评论中所说,稀疏矩阵可以成功显示。
此外,方法
sparseMatrixDisplay
不返回任何内容,仅提供打印非零元素的函数。但如果它在找到这样的元素后立即打印一行,而不是将中间结果保存到方法返回后无用的数组中并将它们一起打印,可能会更节省内存。
static void sparseMatrixDisplay(int[][] matrix) {
System.out.println("\nElements of Sparse matrix are:");
int rowCount = matrix.length, colCount = matrix[0].length;
for (int i = 0; i < rowCount; ++i) {
for (int j = 0; j < colCount; ++j) {
if (matrix[i][j] != 0) {
System.out.printf("\t%d\t%d\t%d\n", i, j, matrix[i][j]);
}
}
}
}
附注您可以使用 C 风格的数组类型声明,例如
int matrix[][]
。不过,建议使用Java风格的数组类型声明int[][] matrix
。