`

Leetcode - Sudoku Solver

 
阅读更多
[分析] 做Valid Sudoku时表示3*3区块的下标想得很纠结,其实动手把81个格子的坐标都写出来,左上角为(0,0),这个过程中就能发现坐标规律,越勤奋会越聪明~  这道题目虽然被判为Hard,但看到答案后其实并不难,回溯的题目是有模式可循的,虽然我现在还不是很熟练,但多加练习一定能掌握。早上看到一大神的话,能5天刷一遍leetcode时再问咋还不熟呢,与大家共勉~ 另看参考Code_Ganker的解法:http://blog.csdn.net/linhuanmars/article/details/20748761

public class Solution {
    boolean[][] rows = new boolean[9][9];
    boolean[][] cols = new boolean[9][9];
    boolean[][] blocks = new boolean[9][9];
    public void solveSudoku(char[][] board) {
        clean();
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') {
                    int digitIdx = board[i][j] - '1';
                    rows[i][digitIdx] = true;
                    cols[j][digitIdx] = true;
                    blocks[i / 3 * 3 + j / 3][digitIdx] = true;
                }
            }
        }
        solve(board, 0);
    }
    private boolean solve(char[][] board, int idx) {
        while (idx < 81 && board[idx / 9][idx % 9] != '.')
            idx++;
        if (idx == 81)
            return true;
        int row = idx / 9, col = idx % 9, blockId = row / 3 * 3 + col / 3;
        for (int i = 0; i < 9; i++) {
            if (rows[row][i] || cols[col][i] || blocks[blockId][i])
                continue;
            board[row][col] = (char)('1' + i);
            rows[row][i] = cols[col][i] = blocks[blockId][i] = true;
            if (solve(board, idx + 1))
                return true;
            board[row][col] = '.';
            rows[row][i] = cols[col][i] = blocks[blockId][i] = false;
        }
        return false;
    }
    private void clean() {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                rows[i][j] = false;
                cols[i][j] = false;
                blocks[i][j] = false;
            }
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics