当前位置: 首页 > 工具软件 > Sudoku > 使用案例 >

sudoku-solver

裴泰平
2023-12-01
https://leetcode.com/problems/sudoku-solver/
public class Solution {
    private static boolean isValid(char[][] board, int i, int j) {
        for (int k = 0; k < 9; k++) {
            if (k != j && board[i][k] == board[i][j])
                return false;
        }
        for (int k = 0; k < 9; k++) {
            if (k != i && board[k][j] == board[i][j])
                return false;
        }
        for (int row = i / 3 * 3; row < i / 3 * 3 + 3; row++) {
            for (int col = j / 3 * 3; col < j / 3 * 3 + 3; col++) {
                if ((row != i || col != j) && board[row][col] == board[i][j])
                    return false;
            }
        }
        return true;
    }

    public static boolean solve(char[][] board, int i, int j) {

        if (i >= 9) {
            return true;
        } else {
            //换行
            if (j >= 9) {
                return solve(board, i + 1, 0);
            }
            //当前为数字,不需处理直接处理下一节点。
            if (board[i][j] != '.') {
                return solve(board, i, j + 1);
            } else {
                for (int k = 1; k <= 9; k++) {
                    board[i][j] = (char) (k + '0');
                    if (isValid(board, i, j)) {
                        // !!!WRONG!!!: return solve(board, i, j + 1);
                        if (solve(board, i, j + 1))
                            return true;
                    }
                    board[i][j] = '.';
                }
            }
            return false;
        }
    }

    public  void solveSudoku(char[][] board) {
        if (board == null || board.length != 9 || board[0].length != 9)
            return;
        solve(board, 0, 0);
    }
}

 类似资料: