稀疏数组
稀疏数组
以下代码把11*11的棋盘转化为稀疏数组,再把稀疏数组转化为普通的矩阵(即棋盘)。
package com.cxf.array;
import java.util.Arrays;
public class Demo2 {
public static void main(String[] args) {
int[][] chess1 = new int[11][11];
int num_val = 0;
int count = 1;
chess1[2][3] = 1;
chess1[3][4] = 2;
System.out.println("Original chess board:");
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
System.out.print(chess1[i][j]+"\t");
if(chess1[i][j] != 0) {
num_val++;
}
}
System.out.println();
}
int[][] sparse = new int[num_val + 1][3]; //create a sparse matrix
sparse[0][0] = 11;
sparse[0][1] = 11;
sparse[0][2] =num_val;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(chess1[i][j] != 0) {
sparse[count][0] = i;
sparse[count][1] = j;
sparse[count][2] = chess1[i][j];
count++;
}
}
}
System.out.println("==========================================");
System.out.println("sparce matrix:");
for (int i = 0; i < num_val + 1; i++) {
System.out.println(Arrays.toString(sparse[i]));
}
System.out.println("==========================================");
System.out.println("turn the sparce matrix to chess board:");
int[][] chess2 = new int[sparse[0][0]][sparse[0][1]];
for (int i = 1; i <= sparse[0][2]; i++) {
chess2[sparse[i][0]][sparse[i][1]] = sparse[i][2];
}
//print chess2
for (int[] ints : chess2) {
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
}
}
输出结果:
Original chess board:
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 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
==========================================
sparce matrix:
[11, 11, 2]
[2, 3, 1]
[3, 4, 2]
==========================================
turn the sparce matrix to chess board:
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 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
稀疏数组只记录普通数组中特殊点的位置和值。