package com.zhangwl.数据结构.稀疏数组; /** * @ClassName SparseArray * @Description 棋盘游戏演示 * @Author zhangwl * @Date 2019/10/10 22:54 * @Version 1.0 **/public class SparseArray { public static void main(String[] args) { /*创建一个原始的二维数组11 * 11 ,0:表示没有棋子 ;1:表示黑子;2:表示蓝子*/ int[][] chessArr = new int[11][11]; chessArr[1][2] = 1; chessArr[2][3] = 2; System.out.println("原始的二维数组~~"); for (int[] row : chessArr) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } System.out.println("************************二维数组转换为稀疏数组*********************************"); /*1、先遍历二位数组得到非0元素的个数*/ int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if (chessArr[i][j] != 0) { sum++; } } } /*2、创建对应的稀疏数组*/ int[][] sparseArr = new int[sum + 1][3]; /*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 (chessArr[i][j] != 0) { count++; sparseArr[count][0] = i; sparseArr[count][1] = j; sparseArr[count][2] = chessArr[i][j]; } } } System.out.println("遍历稀疏数组~~"); for (int[] row : sparseArr) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } System.out.println("************************稀疏数组转换为二维数组*********************************"); int rowLen = sparseArr[0][0]; int colLen = sparseArr[0][1]; int[][] origionChessArr = new int[rowLen][colLen]; System.out.println("输出恢复后的二维数组1~~"); for (int[] row : origionChessArr) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } /*利用稀疏数组给原始数组进行赋值*/ for (int i = 1; i < sparseArr.length; i++) { int tempRowLen = sparseArr[i][0]; int tempColLen = sparseArr[i][1]; int tempArrVal = sparseArr[i][2]; origionChessArr[tempRowLen][tempColLen] = tempArrVal; } System.out.println("输出恢复后的二维数组2~~"); for (int[] row : origionChessArr) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } }} 运行结果:
原始的二维数组~~
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
************************二维数组转换为稀疏数组*********************************
遍历稀疏数组~~
11 11 2
1 2 1
2 3 2
************************稀疏数组转换为二维数组*********************************
输出恢复后的二维数组1~~
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
输出恢复后的二维数组2~~
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
原文地址:https://www.cnblogs.com/sico/p/11651443.html