生活随笔
收集整理的這篇文章主要介紹了
【数据结构】稀疏数组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
稀疏數組保存五子棋棋盤
思路:二維數組模擬棋盤 --->稀疏數組--->序列化到文件中保存--->反序列化得到稀疏數組--->還原二維數組
??對象序列化需要實現Serializable接口。要是是我們定義的對象那好辦,直接在類的后面加一句implements Serializable就可以了。思路是定義一個類,然后定義一個二維數組的屬性,然后操作這個類。
??但是,在一開始我正愁沒有類讓我去實現接口,于是我嘗試著直接去序列化了數組,操作居然成功了,這就很神奇,至于為什么暫時不清楚??傊枨笠呀浲瓿闪???创a:
import java.io.*;
import java.util.Arrays;
public class SparseArray {public static void main(String[] args
) {int chessArr1
[][] = new int[11][11];chessArr1
[1][2] = 1;chessArr1
[2][2] = 2;chessArr1
[3][2] = 1;for (int[] rows
: chessArr1
) {for (int row
: rows
) {System.out
.printf("%d\t",row
);}System.out
.println();}int sum
= 0;for (int i
= 0; i
< chessArr1
.length
; i
++) {for (int j
= 0; j
< chessArr1
.length
; j
++) {if (chessArr1
[i
][j
] != 0){sum
++;}}}int [][] sparseArr
= new int[sum
+ 1][3];sparseArr
[0][0] = chessArr1
.length
;sparseArr
[0][1] = chessArr1
.length
;sparseArr
[0][2] = sum
;int count
= 0;for (int i
= 0; i
< chessArr1
.length
; i
++) {for (int j
= 0; j
< chessArr1
.length
; j
++) {if (chessArr1
[i
][j
] != 0){count
++;sparseArr
[count
][0] = i
;sparseArr
[count
][1] = j
;sparseArr
[count
][2] = chessArr1
[i
][j
];}}}System.out
.println("得到的稀疏數組:");for (int[] rows
: sparseArr
) {for (int row
: rows
) {System.out
.printf("%d\t",row
);}System.out
.println();}try {ObjectOutputStream oos
= new ObjectOutputStream(new FileOutputStream("D:\\code\\DataStructuresAndAlgorithms\\DataStructures\\src\\chess.dat"));oos
.writeObject(sparseArr
);oos
.close();} catch (IOException e
) {throw new RuntimeException(e
);}int[][] sparseArr2
= null;try {ObjectInputStream ois
= new ObjectInputStream(new FileInputStream("D:\\code\\DataStructuresAndAlgorithms\\DataStructures\\src\\chess.dat"));sparseArr2
= (int[][]) ois
.readObject();ois
.close();System.out
.println("====反序列化還原的稀疏數組=====");System.out
.println(Arrays.deepToString(sparseArr2
));} catch (Exception e
) {throw new RuntimeException(e
);}int[][] chessArr2
= new int[sparseArr2
[0][0]][sparseArr2
[0][1]];for (int i
= 1; i
< sparseArr2
.length
; i
++) {chessArr2
[sparseArr2
[i
][0]][sparseArr2
[i
][1]] = sparseArr2
[i
][2];}System.out
.println("恢復后的二維數組:");for (int[] rows
: chessArr2
) {for (int row
: rows
) {System.out
.printf("%d\t",row
);}System.out
.println();}}}
運行截圖:
總結
以上是生活随笔為你收集整理的【数据结构】稀疏数组的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。