Data structures: a sparse array

  When most of the elements in an array is 0, or a value of the same array, the sparse array can be used to hold the array.

  Sparse array of treatment methods are:

      ① array of records a total of several odd row, how many different values.

      ② the ranks and values ​​of elements with different values ​​of records in an array of small-scale, thereby reducing the size of the program.

 

 

 Sparse array code examples:

package com.lineStructure;

public class array {
	public static void main(String[] args){
		// 创建一个原始的二维数组
		// 0表示没有棋子  1:黑子  2:白子
		int[][] chessArr = new int[11][11];
		chessArr[1][2] = 1;
		chessArr[2][3] = 2;
		for(int[] row : chessArr){
			for(int data : row){
				System.out.printf("%d\t", data);
			}
			System.out.println();
		}
		
		// 将二维数组转稀疏数组
	    // 1. 先遍历二维数组, 得到非0数据的个数
		int sum = 0;
		for(int i=0; i<chessArr.length;i++){
			for(int j=0; j<chessArr[0].length;j++){
				if(chessArr[i][j] != 0)
					sum++;
			}
		}
		// 2. 创建对应的稀疏数组
		int sparseArr[][] = new int[sum+1][3];
		// 为稀疏数组赋值
		sparseArr[0][0] = 11;  // 保存行
		sparseArr[0][1] = 11;  // 保存列
		sparseArr[0][2] = sum; // 保存个数
		
		// 遍历二维数组,将非0的值存放到稀疏数组中
		int count = 0;
		for(int i=0; i<chessArr.length;i++){
			for(int j=0; j<chessArr[0].length;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 i = 0; i<sparseArr.length;i++){
			
			System.out.printf("%d\t%d\t%d\n", sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
		}
		
		// 将稀疏数组----->恢复成 原始的二维数组
		int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
		
		for(int i=1;i<sparseArr.length;i++){
			chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
		}
		
		// 恢复后的二维数组
		System.out.println("恢复后的二维数组......");
		for(int[] row : chessArr2){
			for(int data : row){
				System.out.printf("%d\t", data);
			}
			System.out.println();
		}
	}
}

 

Guess you like

Origin blog.csdn.net/m0_37564426/article/details/90900313