1、简介

2、稀疏数组


第一行记录左边二维数组共有几行几列和几个非0值
后面8行记录8个数据所在位置和值

package com.atguigu.sparsearray; import java.io.*; import java.util.ArrayList; import java.util.List; public class SparseArray { public static void main(String[] args) throws IOException { //1.创建二维数据 int[][] chessArray1 = new int[11][11]; chessArray1[1][2] = 1; chessArray1[2][3] = 2; chessArray1[2][7] = 2; for (int[] row : chessArray1) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } //二维数组的行数 System.out.println(chessArray1.length); //将二维数组转成稀疏数组 //2.遍历二维数据得到非0的个数 int sum = 0; for (int i = 0; i < chessArray1.length; i++) { for (int j = 0; j < chessArray1[i].length; j++) { //统计不为0的个数 if (chessArray1[i][j] > 0) { sum++; } } } System.out.println(sum); //3.创建稀疏数组 int[][] sparseArray = new int[sum + 1][3]; sparseArray[0][0] = 11; sparseArray[0][1] = 11; sparseArray[0][2] = sum; //4.遍历二维数组给稀疏数组赋值 int count = 0; for (int i = 0; i < chessArray1.length; i++) { for (int j = 0; j < chessArray1[i].length; j++) { if (chessArray1[i][j] > 0) { count++; sparseArray[count][0] = i; sparseArray[count][1] = j; sparseArray[count][2] = chessArray1[i][j]; } } } //5.遍历稀疏数组输出 for (int i = 0; i < sparseArray.length; i++) { for (int j = 0; j < sparseArray[i].length; j++) { System.out.printf("%d\t", sparseArray[i][j]); ; } System.out.println(); } //6.将稀疏数组保存到磁盘 BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("d:\\map.data")); for (int[] row : sparseArray) { bufferedWriter.write(row[0] + "\t" + row[1] + "\t" + row[2]); bufferedWriter.newLine(); } bufferedWriter.close(); //7.从磁盘读取数据 BufferedReader bufferedReader = new BufferedReader(new FileReader("d:\\map.data")); String line; List<Integer> list = new ArrayList<>(); while ((line = bufferedReader.readLine()) != null) { String[] split = line.split("\t"); for (String s : split) { list.add(Integer.parseInt(s)); } } //list 11 11 3 1 2 1 2 3 2 2 7 2 //8.根据读取的数据创建稀疏数组 int[][] sparseArray2 = new int[list.get(2) + 1][3]; int j = 0; for (int i = 0; i < list.size(); i = i + 3) { sparseArray2[j][0] = list.get(i); sparseArray2[j][1] = list.get(i + 1); sparseArray2[j][2] = list.get(i + 2); j++; } int[][] chessArray2 = new int[sparseArray2[0][0]][sparseArray2[0][1]]; //9.稀疏数组恢复二维数组 for (int i = 1; i < sparseArray2.length; i++) { chessArray2[sparseArray2[i][0]][sparseArray2[i][1]] = sparseArray2[i][2]; } for (int[] row : chessArray2) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } } }
3、队列

