Skip to content

Commit 2317da8

Browse files
authored
Create 21_sudokuSolver.cpp
1 parent 03d4b88 commit 2317da8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public:
3+
vector<pair<int, int>> emptyCells;
4+
int rows[9] = {}, cols[9] = {}, boxes[9] = {};
5+
void solveSudoku(vector<vector<char>>& board) {
6+
for (int r = 0; r < 9; r++) {
7+
for (int c = 0; c < 9; c++) {
8+
if (board[r][c] == '.') {
9+
emptyCells.emplace_back(r, c);
10+
} else {
11+
int val = board[r][c] - '0';
12+
int boxPos = (r / 3) * 3 + (c / 3);
13+
rows[r] |= 1 << val;
14+
cols[c] |= 1 << val;
15+
boxes[boxPos] |= 1 << val;
16+
}
17+
}
18+
}
19+
backtracking(board, 0);
20+
}
21+
bool backtracking(vector<vector<char>>& board, int i) {
22+
if (i == emptyCells.size()) return true; // Check if we filled all empty cells?
23+
24+
int r = emptyCells[i].first, c = emptyCells[i].second, boxPos = (r / 3) * 3 + c / 3;
25+
for (int val = 1; val <= 9; ++val) {
26+
if (getBit(rows[r], val) || getBit(cols[c], val) || getBit(boxes[boxPos], val)) continue; // skip if that value is existed!
27+
board[r][c] = ('0' + val);
28+
int oldRow = rows[r], oldCol = cols[c], oldBox = boxes[boxPos]; // backup old values
29+
rows[r] |= 1 << val;
30+
cols[c] |= 1 << val;
31+
boxes[boxPos] |= 1 << val;
32+
if (backtracking(board, i + 1)) return true;
33+
rows[r] = oldRow; // backtrack
34+
cols[c] = oldCol; // backtrack
35+
boxes[boxPos] = oldBox; // backtrack
36+
}
37+
return false;
38+
}
39+
int getBit(int x, int k) {
40+
return (x >> k) & 1;
41+
}
42+
};

0 commit comments

Comments
 (0)