1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| func solveSudoku(board [][]byte) { backtrack(board, 0, 0) }
func backtrack(board [][]byte, i, j int) bool { if j == 9 { return backtrack(board, i + 1, 0) } if i == 9 { return true } if board[i][j] != '.' { return backtrack(board, i, j + 1) }
for n := '1'; n <= '9'; n++ { if !isValid(board, i, j, byte(n)) { continue } board[i][j] = byte(n) if backtrack(board, i, j + 1) { return true } board[i][j] = '.' }
return false }
func isValid(board [][]byte, row, col int, val byte) bool { for i := 0; i < 9; i++ { if board[row][i] == val { return false } if board[i][col] == val { return false } if board[(row/3)*3 + i/3][(col/3)*3 + i%3] == val { return false } } return true }
|