package DataStructures.sparseArray;
import java.io.*;
/**
* @author coffee
* @date 2021-03-29 13:53
*/
public class arrayAndSparseTransformEachOther{
public static void main(String[] args) {
//创建一个原始的11*11的二维数组,0表示没有棋子,1表示黑子,2表示蓝子
int[][] cherryArr1 = new int[11][11];
cherryArr1[1][2] = 1;
cherryArr1[2][3] = 2;
for(int[] i : cherryArr1){
for (int j:i) {
System.out.print(j + "\t");
}
System.out.println();
}
//二维数组转稀疏数组
//遍历数组,得到非0数据的个数
int sum = 0;
for (int i = 0; i < cherryArr1.length; i++) {
for (int j = 0; j < cherryArr1.length; j++) {
if (cherryArr1[i][j] != 0)
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 < cherryArr1.length; i++) {
for (int j = 0; j < cherryArr1.length; j++) {
if (cherryArr1[i][j] != 0){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = cherryArr1[i][j];
}
}
}
//输出稀疏数组
System.out.println("稀疏数组:");
for (int i = 0; i < sparseArr.length; i++) {
for (int j = 0; j < sparseArr.length; j++) {
System.out.print(sparseArr[i][j] + "\t");
}
System.out.println();
}
//将稀疏数组恢复为二维数组
//1.先读取稀疏数组的第一的数据
int[][] cherryArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
//2.再读取稀疏数组的后几行,并赋给二维数组
for (int i = 1; i < sparseArr.length; i++) {
cherryArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
for(int[] i : cherryArr2){
for (int j:i) {
System.out.print(j + "\t");
}
System.out.println();
}
//将稀疏数组保存到磁盘上
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(new File("map.data")));
for (int[] row : sparseArr){
for (int data : row){
bw.write(data + "\t");
}
bw.write("\n");
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//从硬盘中读取稀疏数组
int[][] sparseArr2 = new int[sum + 1][3];
int count1 = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("map.data")));
String len;
while ((len = br.readLine()) != null){
String[] str = len.split("\t");
for (int i = 0; i < str.length; i++) {
sparseArr2[count1][i] = Integer.parseInt(str[i]);
}
count1++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("稀疏数组2:");
for (int i = 0; i < sparseArr2.length; i++) {
for (int j = 0; j < sparseArr2.length; j++) {
System.out.print(sparseArr2[i][j] + "\t");
}
System.out.println();
}
}
}
稀疏数组与二维数组互相转换
最新推荐文章于 2024-09-03 20:29:47 发布