LeetCode 37 Sudoku Solver (C++)

Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.


Solution C++


 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
private:
    static const int N = 9;
    bool intSolveSudoku(int sid, const vector<pair<int, int>>& spaces, vector<vector<char>>& board, 
        vector<bitset<N>>& rows, vector<bitset<N>>& cols, vector<bitset<N>>& boxes, int rlboxmap[N/3][N/3]) {
        if (sid == spaces.size()) return true;
        int i = spaces[sid].first;
        int j = spaces[sid].second;
        int solved = false;
        int boxid = rlboxmap[i/3][j/3];
        bitset<N> num = rows[i] & cols[j] & boxes[boxid];
        for (int k = 0; k < N; ++k) {
            if (num[k] == 0) continue;
            board[i][j] = k + '1';
            rows[i].reset(k);
            cols[j].reset(k);
            boxes[boxid].reset(k);
            if (intSolveSudoku(sid + 1, spaces, board, rows, cols, boxes, rlboxmap)) {
                solved = true;
                break;
            }
            rows[i].set(k);
            cols[j].set(k);
            boxes[boxid].set(k);
            board[i][j] = '.';
        }
        return solved;
    }
public:
    void solveSudoku(vector<vector<char>>& board) {
        vector<bitset<N>> rows;
        vector<bitset<N>> cols;
        vector<bitset<N>> boxes;
        for (int i = 0; i < N; ++i) {
            bitset<N> tmp(string("111111111"));
            rows.push_back(tmp);
            cols.push_back(tmp);
            boxes.push_back(tmp);
        }
        int rlboxmap[N/3][N/3] = {
            {0, 1, 2},
            {3, 4, 5},
            {6, 7, 8}
        };
        vector<pair<int, int>> spaces;
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < N; ++j) {
                if (board[i][j] == '.') {
                    spaces.push_back({i, j});
                    continue;
                }
                rows[i].reset(board[i][j] - '1');
                cols[j].reset(board[i][j] - '1');
                boxes[rlboxmap[i/3][j/3]].reset(board[i][j] - '1');
            }
        }
        intSolveSudoku(0, spaces, board, rows, cols, boxes, rlboxmap);
    }
};

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving