74 lines
1.5 KiB
Go
74 lines
1.5 KiB
Go
package SudokuValidator
|
|
|
|
type SudokuValidator struct {
|
|
rows [9]map[byte]bool
|
|
cols [9]map[byte]bool
|
|
boxes [9]map[byte]bool
|
|
}
|
|
|
|
func NewSudokuValidator() *SudokuValidator {
|
|
validator := &SudokuValidator{}
|
|
for i := 0; i < 9; i++ {
|
|
validator.rows[i] = make(map[byte]bool)
|
|
validator.cols[i] = make(map[byte]bool)
|
|
validator.boxes[i] = make(map[byte]bool)
|
|
}
|
|
return validator
|
|
}
|
|
|
|
func (s *SudokuValidator) isValidRow(row int, num byte) bool {
|
|
if s.rows[row][num] {
|
|
return false
|
|
}
|
|
s.rows[row][num] = true
|
|
return true
|
|
}
|
|
|
|
func (s *SudokuValidator) isValidColumn(col int, num byte) bool {
|
|
if s.cols[col][num] {
|
|
return false
|
|
}
|
|
s.cols[col][num] = true
|
|
return true
|
|
}
|
|
|
|
func (s *SudokuValidator) isValidBox(boxIndex int, num byte) bool {
|
|
if s.boxes[boxIndex][num] {
|
|
return false
|
|
}
|
|
s.boxes[boxIndex][num] = true
|
|
return true
|
|
}
|
|
|
|
func (s *SudokuValidator) IsValidSudoku(board *[][]byte) bool {
|
|
for i := 0; i < 9; i++ {
|
|
for j := 0; j < 9; j++ {
|
|
if (*board)[i][j] != '.' {
|
|
num := (*board)[i][j]
|
|
boxIndex := (i/3)*3 + j/3
|
|
|
|
if !(s.isValidRow(i, num) && s.isValidColumn(j, num) && s.isValidBox(boxIndex, num)) {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// IsValidSudoku2 just for demo purposes
|
|
func (s *SudokuValidator) IsValidSudoku2(board [][]byte) bool {
|
|
for i := 0; i < 9; i++ {
|
|
for j := 0; j < 9; j++ {
|
|
if board[i][j] != '.' {
|
|
num := board[i][j]
|
|
boxIndex := (i/3)*3 + j/3
|
|
|
|
if !(s.isValidRow(i, num) && s.isValidColumn(j, num) && s.isValidBox(boxIndex, num)) {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|