Requirements: There are 11 * 11 board, chess than half want to save and exit
Algorithm idea: the chessboard analog matrix, save only the data location, also known as data compression
package main
import "fmt"
type Node struct{
row int
col int
val int
}
func main() {
// 定义稀疏数组并打印
var Array[11][11] int
Array[1][2] = 2
Array[2][3] = 4
for _, val := range Array{
for _, v := range val{
fmt.Printf("%d\t", v)
}
fmt.Println()
}
// 将稀疏数组数据压缩存放进SparseNode
var SparseNode []Node
firstNode := Node{11,11,0}
SparseNode = append(SparseNode, firstNode)
for i, val := range Array{
for j, v := range val{
if v != 0{
node := Node{
row: i,
col: j,
val: v,
}
SparseNode = append(SparseNode, node)
}
}
}
//将存放的压缩数据打印
for i, node := range SparseNode{
fmt.Printf("%d: %d %d %d\n", i, node.row, node.col, node.val)
}
// 将压缩数据还原成数组
var newArray[11][11] int
for i, node := range SparseNode{
if i !=0{
newArray[node.row][node.col] = node.val
}
}
// 再次验证
for _, val := range newArray{
for _, v := range val{
fmt.Printf("%d\t", v)
}
fmt.Println()
}
}
operation result:
Note:
1, the rows and columns you want to save under the board
2, to remember when reading the first column is the checkerboard rows and columns, or prone to an array of cross-border