package com.itcast.datastructure.sparsearray; public class ChessDemo { public static void main(String[] args) { //创建棋盘 int[][] chessArr1=new int[11][11]; //开始下棋 chessArr1[2][3]=1; chessArr1[4][6]=2; chessArr1[1][5]=1; //转为稀疏数组 int sum=0; for (int[] arr:chessArr1){ for (int i:arr){ if(i!=0){ sum++; } } } System.out.println("sum= "+sum); int[][] sparseArr=new int[sum+1][3]; sparseArr[0][0]=11; sparseArr[0][1]=11; sparseArr[0][2]=sum; int count=0; for (int i=0;i<11;i++) { for (int j = 0; j < 11; j++) { if (chessArr1[i][j] != 0) { count++; sparseArr[count][0] = i; sparseArr[count][1] = j; sparseArr[count][2] = chessArr1[i][j]; } } } //将稀疏数组存入磁盘 //........... //从磁盘读出稀疏数组 //把稀疏数组转为棋盘 int[][] chessArr2=new int[sparseArr[0][0]][sparseArr[0][1]]; for (int i=1;i<=sum;i++){ chessArr2[sparseArr[i][0]][sparseArr[i][1]]=sparseArr[i][2]; } for (int[] arr:chessArr2){ for (int i:arr){ System.out.printf("%d\t",i); } System.out.println(); } } }
数据结构:稀疏数组实现数据压缩
于 2022-04-29 10:01:03 首次发布