稀疏数组

稀疏数组

package main

import "fmt"

type ValueNode struct {
	Row int
	Cloumn int
	Value int
}

type ValueNodeSlice []ValueNode
func main() {
//	1.先创建一个原始数组
	var ChessMap [11][11]int
	ChessMap[1][2] = 1 //黑棋
	ChessMap[2][3]=2 // 蓝棋
//	2.输入看看原始的数组
	for _,v :=range ChessMap{
		for _,v2 :=range v{
			fmt.Printf("%d\t",v2)
		}
		fmt.Println()

	}

		var valueNodeSlice ValueNodeSlice
		valueNodeSlice = append(valueNodeSlice,ValueNode{Row:11,Cloumn:11})
		//fmt.Println(valueNodeSlice)

		for i,v :=range ChessMap{
			for i1,v2 :=range v{
				if v2 != 0 {
					var valuenode ValueNode =ValueNode{i,i1,v2}
					valueNodeSlice=append(valueNodeSlice,valuenode)
				}
			}
		}
		
		#打印稀疏数组
		for i,v :=range valueNodeSlice{
			fmt.Printf("%d: %d %d %d\n",i,v.Row,v.Cloumn,v.Value)
		}

		fmt.Println()
		
		#稀疏数组恢复成老的数组
		fmt.Println("Recover Array")
		var SparseArray2 [11][11]int
		for i,v :=range valueNodeSlice{
			if i == 0 {
				continue
			}
			SparseArray2[v.Row][v.Cloumn] = v.Value
		}
	
	for _,v :=range SparseArray2{
		for _,v2 :=range v{
			fmt.Printf("%d\t",v2)
		}
		fmt.Println()

	}

}

posted @ 2019-09-17 20:20  Egrep  阅读(185)  评论(0编辑  收藏  举报