稀疏数组的转换

package 数组.稀疏数组;

public class 稀疏数组 {
    public static void main(String[] args) {
        // 11*11二维数组,第2行第三列白子9号,第3行第4列黑子6号,将棋盘中的两子的位置和号数 整理到 稀疏数组中
        int arr[][] = new int[11][11];
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                arr[1][2] = 9;
                arr[2][3] = 5;
            }
        }
        /*
            11 11 2
            1  2  9
            2  3  5
         */
        int[][] res = change(arr);
        System.out.println("转为稀疏数组");
        printArr(res);
        System.out.println("再将稀疏数组转为棋盘");
        int[][] a = restore(res);
        printArr(a);
    }

    public static int[][] change(int[][] arr){
        int sum = 0;
        for (int[] ints : arr) {
            for (int num : ints) {
                if (num != 0) {
                    sum++;
                }
                System.out.print(num + "\t");
            }
            System.out.println();
        }
        int count = 0;
        int res[][] = new int[sum + 1][3];
        res[0][0] = arr.length;
        res[0][1] = arr[0].length;
        res[0][2] = sum;
        for (int i = 0; i < arr[0].length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                if (arr[i][j] != 0) {
                    count++;
                    res[count][0] = i;
                    res[count][1] = j;
                    res[count][2] = arr[i][j];
                }
            }
        }
        return res;
    }

    public static int[][] restore(int[][] res){
        int a[][] = new int[res[0][0]][res[0][1]];
        int c = 0;
        for (int i = 0; i < res[0][2]; i++) {
            c++;
            a[res[c][0]][res[c][1]] = res[c][2];
        }
        return a;
    }

    public static void printArr(int[][] arr){
        for (int[] ints : arr) {
            for (int num : ints) {
                System.out.print(num+"\t");
            }
            System.out.println();
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值