Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The
Rules.

The Sudoku board could be partially filled, where empty cells are
filled with the character '.'.

回溯法

说明

对于每一个空格进行从1-9的验证, 如果错误则向前回溯
这道题迭代的方法要注意, 因为它是一个二维的矩阵, 当每一行迭代完之后我们要让他进行下一行的验证

每个节点都要测试9个数, 一共9^2个节点, 每次还要验证横行, 竖行, block一共3*9
时间O(9^4)

代码

public void solveSudoku(char[][] board) {
    if (board == null || board.length < 9 || board[0].length < 9) {
        return;
    }
    helper(board, 0, 0);
}
public boolean helper(char[][] board, int m, int n) {
   if (n >= 9) {
       return helper(board, m + 1, 0);
   }
   if (m == 9) {
       return true;
   }
   if (board[m][n] == '.') {
       for (char i = '1'; i <= '9'; i++) {
           board[m][n] = i;
           if (isValid(board, m, n)) {
               if (helper(board, m, n + 1)) {
                   return true;
               }
           }
           board[m][n] = '.';
       }
   } else {
       return helper(board, m, n+ 1);
   }
   return false;
}
public boolean isValid(char[][] board, int m, int n) {
    for (int i = 0; i < 9; i++) {
        if (i != m && board[i][n] == board[m][n]) {
            return false;
        }
    }
    for (int i = 0; i < 9; i++) {
        if (i != n && board[m][i] == board[m][n]) {
            return false;
        }
    }
    for (int i = m / 3 * 3; i< m / 3 * 3 + 3; i++) {
        for (int j = n /3 * 3; j < n / 3 *3 + 3; j++) {
            if (i != m && j != n && board[i][j] == board[m][n]) {
                return false;
            }
        }
    }
    return true;
}

lpy1990
26 声望10 粉丝

下一篇 »
Add Binary