037. 解数独 Sudoku Solver

Description hard

编写一个程序,通过已填充的空格来解决数独问题。

一个数独的解法需遵循如下规则:

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
  4. 空白格用 '.' 表示。

sudo 一个数独

sudo

答案被标称红色

说明:

Example
输入:
[
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
输出: 把点换成数字
Solution
func solveSudoku(board [][]byte)  {
    if board == nil  || len(board) != 9 || len(board[0]) != 9  {
        return
    }
    helper(board)
}

func helper(board [][]byte)bool  {
    for row := range board {
        for col := range board[row] {
            if board[row][col] == '.' {
                for num := '1';num <= '9';num ++ {
                    if isValid(board,byte(row),byte(col),byte(num)) {
                        board[row][col] = byte(num)
                        if helper(board) {
                            return true
                        }else {
                            board[row][col] = '.'
                        }
                    }
                }
                return false
            }

        }
    }
    return true
}

func isValid(board [][]byte,row,col int ,num byte)bool  {
    //check row & col
    for i := 0;i < 9 ; i  ++ {
        if board[i][col] == num {
            return false
        }
        if board[row][i] == num {
            return false
        }
    }
    //check block
    for  i := (row/3)*3;i < (row/3)*3 +3;i ++ {
        for j := (col/3)*3; j < (col/3)*3 +3;j ++ {
            if board[i][j] == num {
                return false
            }
        }

    }
    return true
}

leetCode地址