入门级稀松数组

编程

`package com.bianmirj;

/**

  • 数组的稀松算法

    */

public class ScarceArray {

public static void main(String[] args) {

    //准备好源数组

int chessArr1[][] = new int[11][11];

chessArr1[1][2] = 1;

chessArr1[2][3] = 2;

chessArr1[4][5] = 2;

for (int[] row : chessArr1) {

for (int data : row) {

System.out.printf("%d ", data);

}

System.out.println();

}

/*

稀疏数组的原理

0 11 11 3 //11行 11列 3个元素

1 1 2 1

2 2 2 2

3 4 5 2

*/

//先求出总行 总列

int col = 11;

int row = 11;

int sum = 0;

for (int[] vv : chessArr1) {

for (int v : vv) {

if (v != 0) {

sum++;

}

}

}

toScarceArray(chessArr1, sum);

}

public static void toScarceArray(int[][] arr, int num) {

int[][] newArr = new int[num + 1][3];

newArr[0][0] = 11;

newArr[0][1] = 11;

newArr[0][2] = num;

int temp = 1;

for (int i = 0; i < arr.length; i++) {

for (int j = 0; j < arr[i].length; j++) {

if (arr[i][j] != 0) {

newArr[temp][0] = i;

newArr[temp][1] = j;

newArr[temp][2] = arr[i][j];

temp++;

}

}

}

for (int[] row : newArr) {

for (int data : row) {

System.out.printf("%d ", data);

}

System.out.println();

}

toEasyArray(newArr);

}

public static void toEasyArray(int[][] arr) {

int c = arr[0][0];

int r = arr[0][1];

int chessArr1[][] = new int[c][r];

for (int i = 0; i < arr.length; i++) {

if (i != 0) {

int coll = arr[i][0];

int rowl = arr[i][1];

System.out.println(coll + "-" + rowl);

chessArr1[coll][rowl] = arr[i][2];

}

}

for (int[] row : chessArr1) {

for (int data : row) {

System.out.printf("%d ", data);

}

System.out.println();

}

}

}

`

以上是 入门级稀松数组 的全部内容, 来源链接: utcz.com/z/517209.html

回到顶部