稀疏数组

-----原棋盘------
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    2    0    0    0    0    0    0    0    
0    0    0    0    4    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    

像这样的数据保存的话,可以进行压缩保存

把原行列总数保存来记录大小,行列对应的值保存来记录值

这样可以根据这些数据进行换原了

package com.atguigu

import scala.collection.mutable.ArrayBuffer

/**
  * @author wade 
  * @create 2019-03-28 21:35 
  */
object SparseArr {

  def main(args: Array[String]): Unit = {
        val chessMap1: Array[Array[Int]] = Array.ofDim[Int](11,11)
        chessMap1(2)(3)=2
        chessMap1(3)(4)=4
      //打印原棋盘
    println("-----原棋盘------")
        for(i <- 0 until chessMap1.length){
          for(j <- 0 until chessMap1(i).length){
              print(s"${chessMap1(i)(j)}\t")
          }
          println()
        }

      //压缩棋盘
      //把棋盘 总长宽 存起来
    val size = new Node(11,11,0)
    val nodes = new ArrayBuffer[Node]()
    nodes+=size
    for(i <- 0 until chessMap1.length){
      for(j <- 0 until chessMap1(i).length){
       if(chessMap1(i)(j) != 0){
         nodes += new Node(i,j,chessMap1(i)(j))
       }

      }

    }
    //打印保存后的棋盘  size 那一条先不打印
    println("保存后的棋盘")
    for(i <- 1 until nodes.size){
      val node = nodes(i)
      println(s"${node.row}\t${node.col}\t${node.value}")
    }

    //还原成原先的棋盘
    //先还原大小
    val chessMap2: Array[Array[Int]] = Array.ofDim[Int](nodes(0).row,nodes(0).col)
      for(i <- 1 until nodes.size){
        val node = nodes(i)
        chessMap2(node.row)(node.col)=node.value
      }
    println("打印还原的棋盘")
    for( i <- 0 until chessMap2.length){
      for(j <- 0 until chessMap2(i).length){
        print(s"${chessMap2(i)(j)}\t")
      }
      println()
    }
  }
}

class Node(val row:Int,val col:Int,val value:Int)

猜你喜欢

转载自blog.csdn.net/qq_42506914/article/details/88879760