稀疏算法Sparse
package 稀疏算法; import sun.text.resources.in.FormatData_in; import java.lang.reflect.Array; /** * @author Wxy * @data 2020/2/1 - 17:56 **/ public class Sparse { public static void main(String[] args) { //定义一个二维数组 int[][] chessArr = new int[11][11]; chessArr[1][2] = 1; chessArr[2][3] = 2;
chessArr[2][4] = 2; for (int[] row:chessArr) { for (int data:row) { System.out.printf(" "+data); } System.out.println(); } //将棋盘转换为稀疏数组 //先遍历二维数组得到非0的数据 int sum = 0; for (int i = 0; i <11 ; i++) { for (int j = 0; j <11 ; j++) { if(chessArr[i][j] != 0) { sum++; } } } //创建对应的稀疏数组 int[][] sparseArr = new int[sum+1][3]; sparseArr[0][0] = 11; sparseArr[0][1] = 11; sparseArr[0][2] = sum; //遍历二维数组得到非0的数据 int count = 0; for (int i = 0; i <11 ; i++) { for (int j = 0; j <11 ; j++) { if (chessArr[i][j] != 0) { count++; sparseArr[count][0] = i; sparseArr[count][1] = j; sparseArr[count][2] = chessArr[i][j]; } } } //输出稀疏数组 System.out.println("得到的稀疏数组为"); for (int i = 0; i <sparseArr.length ; i++) { System.out.println(" " +sparseArr[i][0]+" "+sparseArr[i][1]+" "+sparseArr[i][2]); } System.out.println(); //将稀疏数组转为棋盘 //将稀疏数组的值付给棋盘 int[][] chessArr1 = new int[sparseArr[0][0]][sparseArr[0][1]]; for (int i = 1; i <sparseArr.length ; i++) { chessArr1[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2]; } //打印棋盘 for (int[] row:chessArr1) { for (int data:row) { System.out.printf(" "+data); } System.out.println(); } } }