首页 > 其他分享 >稀疏数组

稀疏数组

时间:2022-09-19 22:36:17浏览次数:66  
标签:int ++ 稀疏 array01 array02 数组 length

什么是稀疏数组
  在使用数组的过程中,需要模拟一些场景,如果把未使用的数组也在数组中分配的化,会占用很大的资源,例如一个五子棋游戏,11x11的棋盘,0表示空,1表示白棋,2表示黑棋,如果此时分配一个  int[][] array01 = new int[11][11];   这样就会浪费资源,所以我们就可以压缩数组,将对应位置的索引和值记录,这样二位数组的中的每个一维数组存储3个数据几个,一维数组的个数由非0的个数决定,看代码:

package com.shiy.array;

import java.util.Arrays;

public class XishuShuzu {
    public static void main(String[] args) {
        int[][] array01 =  new int[11][11];
        array01[1][2] = 1;
        array01[2][3] = 2;
        System.out.println("输出原数组:");

        for (int i = 0; i < array01.length; i++) {
            System.out.println(Arrays.toString(array01[i]));
        }
        System.out.println("输出稀疏数组:");
        int sum = 0;
        for (int i = 0; i < array01.length; i++) {
            for (int j = 0; j < array01.length; j++) {
                if (array01[i][j] != 0){
                    sum++;
                }
            }
        }

        int[][] array02 = new int[sum+1][3];
        array02[0][0] = array01.length;
        array02[0][1] = array01.length;
        array02[0][2] = sum;
        int n = 1;
        for (int i = 0; i < array01.length; i++) {
            for (int j = 0; j < array01.length; j++) {
                if (array01[i][j] != 0){
                    array02[n][0] = i;
                    array02[n][1] = j;
                    array02[n][2] = array01[i][j];
                    n++;
                }
            }
        }
        for (int i = 0; i < array02.length; i++) {
            System.out.println(Arrays.toString(array02[i]));
        }
        System.out.println("还原稀疏数组");

        int[][] array03 = new int[array02[0][0]][array02[0][1]];
        for (int i = 1; i < array02.length; i++) {
            array03[array02[i][0]][array02[i][1]] = array02[i][2];
        }
        for (int i = 0; i < array03.length; i++) {
            System.out.println(Arrays.toString(array01[i]));
        }
    }


}

 

标签:int,++,稀疏,array01,array02,数组,length
From: https://www.cnblogs.com/teststack/p/16709346.html

相关文章