1 import java.io.*; 2 3 /** 4 * @author ZhiYi Li 5 * @create 2020/8/24 10:47 6 * 普通矩阵转稀疏矩阵,稀疏矩阵转普通矩阵,稀疏矩阵的物理存储 7 */ 8 public class SparseArr { 9 public static void main(String[] args) { 10 //构建一个普通矩阵 11 int[][] first = new int[11][12]; 12 first[2][2]=1; 13 first[3][4]=2; 14 //输出普通矩阵 15 System.out.println("生成的普通稀疏矩阵:"); 16 for (int i = 0; i < 11; i++) { 17 for (int j = 0; j < 10; j++) { 18 System.out.print(first[i][j]+" "); 19 } 20 System.out.println(); 21 } 22 //转换为稀疏矩阵 23 //遍历普通矩阵查找非0元素 24 int sum=0; 25 for (int i = 0; i < 11; i++) { 26 for (int j = 0; j < 10; j++) { 27 if(first[i][j]!=0){ 28 sum++; 29 } 30 } 31 } 32 //构建稀疏矩阵 33 int[][] second = new int[sum+1][3]; 34 //存入第一行 35 second[0][0] = first.length; 36 second[0][1] = first[0].length; 37 second[0][2] = sum; 38 //遍历有效节点依次存入稀疏矩阵 39 int temp = 0; 40 for (int i = 0; i < first.length; i++) { 41 for (int j = 0; j < first[0].length; j++) { 42 if(first[i][j]!=0){ 43 temp++; 44 second[temp][0] = i; 45 second[temp][1] = j; 46 second[temp][2] = first[i][j]; 47 } 48 } 49 } 50 //输出稀疏矩阵 51 System.out.println("转换后的稀疏矩阵如下:"); 52 for (int[] ints : second) { 53 for (int j : ints) { 54 System.out.print(j + " "); 55 } 56 System.out.println(); 57 } 58 //稀疏矩阵转普通矩阵 59 System.out.println("稀疏矩阵转普通矩阵:"); 60 int[][] four =new int[second[0][0]][second[0][1]]; 61 for (int i = 1; i < second.length; i++) { 62 four[second[i][0]][second[i][1]] = second[i][2]; 63 } 64 for(int[] ints:four){ 65 for (int item : ints){ 66 System.out.print(item+ " "); 67 } 68 System.out.println(); 69 } 70 //物理存储稀疏矩阵 71 try { 72 FileWriter file = new FileWriter("test.data"); 73 BufferedWriter writer =new BufferedWriter(file); 74 for(int[] data : second){ 75 for(int item : data){ 76 writer.write(item +" "); 77 } 78 writer.newLine();//文件换行 79 } 80 writer.close(); 81 file.close(); 82 } catch (IOException e) { 83 e.printStackTrace(); 84 } 85 86 //读取并输出普通矩阵 87 System.out.println("物理读取稀疏矩阵如下:"); 88 try { 89 FileReader fileReader = new FileReader("test.data"); 90 BufferedReader bufferedReader = new BufferedReader(fileReader); 91 String str = bufferedReader.readLine(); 92 String[] s = str.split(" "); 93 int[][] third = new int[Integer.parseInt(s[0])][Integer.parseInt(s[1])]; 94 while ((str = bufferedReader.readLine())!=null){ 95 String[] s1 = str.split(" "); 96 third[Integer.parseInt(s1[0])][Integer.parseInt(s1[1])] = Integer.parseInt(s1[2]); 97 } 98 for (int[] ints : third) { 99 for (int j : ints) { 100 System.out.print(j + " "); 101 } 102 System.out.println(); 103 } 104 bufferedReader.close(); 105 fileReader.close(); 106 } catch (IOException e) { 107 e.printStackTrace(); 108 } 109 } 110 }
【Java】普通矩阵与稀疏矩阵的互相转化,稀疏矩阵的物理存储
原文:https://www.cnblogs.com/lilice/p/13553137.html