原题链接:link.
使用map记录数独
//方法1 初始化一个空的多维映射
func isValidSudoku(board [][]byte) bool {
row := map[int]map[byte]int{} //存放
column := map[int]map[byte]int{}
box := map[int]map[byte]int{}
for i:=0;i<9;i++{
row[i] = map[byte]int{}
column[i] = map[byte]int{}
box[i] = map[byte]int{}
}
for r:=0;r<9;r++{
for c:=0;c<9;c++{
if board[r][c]=='.'{
continue
}
boxindex := r / 3 * 3 + c / 3
_, row_judge := row[r][board[r][c]]
if row_judge==true{
return false
}
_, column_judge := column[c][board[r][c]]
if column_judge==true{
fmt.Printf("out column")
return false
}
_, box_judge := box[boxindex][board[r][c]]
if box_judge==true{
fmt.Printf("out box")
return false
}
row[r][board[r][c]] = 1
column[c][board[r][c]] = 1
box[boxindex][board[r][c]] = 1
}
}
return true
}
//方法二使用make声明一个多维映射(等同一般声明),该方法比方法一速度更慢一点
func isValidSudoku(board [][]byte) bool {
row := make(map[int]map[byte]int) //存放
column := make(map[int]map[byte]int)
box := make(map[int]map[byte]int)
// sub_row := make(map[byte]int)
// sub_column := make(map[byte]int)
// sub_box := make(map[byte]int)
for i:=0;i<9;i++{
row[i] = make(map[byte]int)
column[i] = make(map[byte]int)
box[i] = make(map[byte]int)
}
for r:=0;r<9;r++{
for c:=0;c<9;c++{
// fmt.Println(board[r][c])
if board[r][c]=='.'{
// fmt.Println(board[r][c])
continue
}
boxindex := r / 3 * 3 + c / 3
_, row_judge := row[r][board[r][c]]
if row_judge==true{
// fmt.Printf("out row")
// fmt.Println(r, c)
return false
}
_, column_judge := column[c][board[r][c]]
if column_judge==true{
fmt.Printf("out column")
return false
}
_, box_judge := box[boxindex][board[r][c]]
if box_judge==true{
fmt.Printf("out box")
return false
}
row[r][board[r][c]] = 1
column[c][board[r][c]] = 1
box[boxindex][board[r][c]] = 1
}
}
return true
}
方法三使用interface{}初始化一个一维映射,需要进行断言对数据类型进行转换,该方法
func isValidSudoku(board [][]byte) bool {
row := map[int]interface{}{} //存放
column := map[int]interface{}{}
box := map[int]interface{}{}
// sub_row := make(map[byte]int)
// sub_column := make(map[byte]int)
// sub_box := make(map[byte]int)
for i:=0;i<9;i++{
row[i] = make(map[byte]int)
column[i] = make(map[byte]int)
box[i] = make(map[byte]int)
}
for r:=0;r<9;r++{
for c:=0;c<9;c++{
// fmt.Println(board[r][c])
if board[r][c]=='.'{
// fmt.Println(board[r][c])
continue
}
boxindex := r / 3 * 3 + c / 3
_, row_judge := row[r].(map[byte]int)[board[r][c]] //对数据类型进行实例化
if row_judge==true{
// fmt.Printf("out row")
// fmt.Println(r, c)
return false
}
_, column_judge := column[c].(map[byte]int)[board[r][c]]这个
if column_judge==true{
fmt.Printf("out column")
return false
}
_, box_judge := box[boxindex].(map[byte]int)[board[r][c]]
if box_judge==true{
fmt.Printf("out box")
return false
}
row[r].(map[byte]int)[board[r][c]] = 1
column[c].(map[byte]int)[board[r][c]] = 1
box[boxindex].(map[byte]int)[board[r][c]] = 1
}
}
return true
}