Home LeetCode. 37. Sudoku Solver
Post
Cancel

LeetCode. 37. Sudoku Solver

image

[Link] https://leetcode.com/problems/sudoku-solver/


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
class Solution {
    char[][] b;
    public void solveSudoku(char[][] board) {
        int len = board.length;
        b = board;
        solve();
    }

    boolean solve() {
        for(int i = 0; i < 9; i++) {
            for(int j = 0; j < 9; j++) {
                if(b[i][j] == '.') {
                    for(char k = '1'; k <= '9'; k++) {
                        if(canput(i, j, k)) {
                            b[i][j] = k;
                            if(solve()) return true;
                        }
                    }
                    b[i][j] = '.';
                    return false;
                }
            }
        }
        return true;
    }

    boolean canput(int row, int col, char v) {
        for(int i = 0; i < 9; i++) if(b[i][col] == v || b[row][i] == v) return false;
        for(int si = 3 * (row / 3), i = si; i < si + 3; i++)
            for(int sj = 3*(col/3), j = sj; j < sj + 3; j++) if(b[i][j] == v) return false;
        return true;
    }
}
This post is licensed under CC BY 4.0 by the author.