/**
* 稀疏矩阵算法
*/
public class SparseMatrix {
/**
* 矩阵转稀疏矩阵
* @param arr
* @return
*/
public static int[][] arrToSparse(int[][] arr){
int cl = 1;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if(arr[i][j] != 0){
cl++;
}
}
}
int[][] sarr = new int[cl][3];
sarr[0][0] = arr.length;
sarr[0][1] = arr[0].length;
sarr[0][2] = cl - 1;
int count = 1;
for (int i = 0; i <arr.length ; i++) {
for (int j = 0; j < arr[i].length; j++) {
if(arr[i][j] != 0){
sarr[count][0] = i;
sarr[count][1] = j;
sarr[count][2] = arr[i][j];
count++;
}
}
}
return sarr;
}
/**
* 稀疏矩阵转完整矩阵
* @param arr
* @return
*/
public static int[][] sparseToArr(int[][] arr){
int[][] rarr = new int[arr[0][0]][arr[0][1]];
for (int i = 1; i <= arr[0][2]; i++) {
rarr[arr[i][0]][arr[i][1]] = arr[i][2];
}
return rarr;
}
public static void main(String[] args) {
int[][] arr = new int[11][11];
arr[1][2] = 1;
arr[2][3] = 2;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.printf("%d \t",arr[i][j]);
}
System.out.printf("\n");
}
//转
int[][] sarr = arrToSparse(arr);
for (int i = 0; i < sarr.length; i++) {
for (int j = 0; j < sarr[i].length; j++) {
System.out.printf("%d \t",sarr[i][j]);
}
System.out.printf("\n");
}
//返
int[][] rarr = sparseToArr(sarr);
for (int i = 0; i < rarr.length; i++) {
for (int j = 0; j < rarr[i].length; j++) {
System.out.printf("%d \t",rarr[i][j]);
}
System.out.printf("\n");
}
}
}
java-稀疏矩阵简单范例
最新推荐文章于 2023-06-04 21:10:19 发布