1. 程式人生 > 實用技巧 >【Java】普通矩陣與稀疏矩陣的互相轉化,稀疏矩陣的物理儲存

【Java】普通矩陣與稀疏矩陣的互相轉化,稀疏矩陣的物理儲存

  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 }