zoukankan      html  css  js  c++  java
  • 将二维数组转为稀疏数组

    public class SparseArray {
    	/**
    	 * 用二维数组实现一个棋盘,1代表黑子,2代表蓝子
    	 */
    	public static void main(String[] args) {
    		/**
    		 * 二维数组
    		 */
    		int[][] chessArray1 = new int[11][11];
    		chessArray1[1][2] = 1;
    		chessArray1[2][3] = 2;
    		for (int[] row : chessArray1) {
    			for (int data : row) {
    				System.out.printf("%d	", data);
    			}
    			System.out.println();
    		}
    		System.out.println("_________________________________________________________________________________");
    		/**
    		 * 将此二维数组转为稀疏数组
    		 */
    		// 先遍历二维数组,得到有几个非零数据
    		int sum = 0;
    		for (int[] row : chessArray1) {
    			for (int data : row) {
    				if (data != 0) {
    					sum++;
    				}
    			}
    		}
    		// 构造稀疏数组
    		int[][] sparseArray = new int[sum + 1][3];
    		sparseArray[0][0] = chessArray1.length;
    		sparseArray[0][1] = chessArray1[0].length;
    		sparseArray[0][2] = sum;
    		// 遍历二维数组,并将非零元素填充到稀疏数组中
    		int count = 0;
    		for (int i = 0; i < chessArray1.length; i++) {
    			for (int j = 0; j < chessArray1[0].length; j++) {
    				if (chessArray1[i][j] != 0) {
    					count++;
    					sparseArray[count][0] = i;
    					sparseArray[count][1] = j;
    					sparseArray[count][2] = chessArray1[i][j];
    				}
    			}
    		}
    		// 打印稀疏数组
    		for (int[] row : sparseArray) {
    			for (int data : row) {
    				System.out.printf("%d	", data);
    			}
    			System.out.println();
    		}
    	}
    
    }
    

      

  • 相关阅读:
    事件总线demo
    软件架构分类(转载)
    ASP.NET MVC 使用 Datatables (2)
    ASP.NET MVC 使用 Datatables (1)
    查看win10的激活信息和版本号
    2016年工作计划
    通俗粗暴的事件委托理解
    matplotlib系列——条形图
    matplotlib系列——折线图
    使用pip安装python模块和包
  • 原文地址:https://www.cnblogs.com/dashenaichicha/p/12675087.html
Copyright © 2011-2022 走看看