public class SparseArray { /** * 用二维数组实现一个棋盘,1代表黑子,2代表蓝子 */ public static void main(String[] args) { /** * 二维数组 */ int[][] chessArray1 = new int[11][11]; chessArray1[1][2] = 1; chessArray1[2][3] = 2; for (int[] row : chessArray1) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } System.out.println("_________________________________________________________________________________"); /** * 将此二维数组转为稀疏数组 */ // 先遍历二维数组,得到有几个非零数据 int sum = 0; for (int[] row : chessArray1) { for (int data : row) { if (data != 0) { sum++; } } } // 构造稀疏数组 int[][] sparseArray = new int[sum + 1][3]; sparseArray[0][0] = chessArray1.length; sparseArray[0][1] = chessArray1[0].length; sparseArray[0][2] = sum; // 遍历二维数组,并将非零元素填充到稀疏数组中 int count = 0; for (int i = 0; i < chessArray1.length; i++) { for (int j = 0; j < chessArray1[0].length; j++) { if (chessArray1[i][j] != 0) { count++; sparseArray[count][0] = i; sparseArray[count][1] = j; sparseArray[count][2] = chessArray1[i][j]; } } } // 打印稀疏数组 for (int[] row : sparseArray) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } } }
原文地址:https://www.cnblogs.com/dashenaichicha/p/12675087.html
时间: 2024-10-10 00:26:26