|
| 1 | +#include <bits/stdc++.h> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +class Solution { |
| 6 | +public: |
| 7 | + void solveSudoku(vector<vector<char>>& board) { |
| 8 | + int size = board.size(); |
| 9 | + vector<vector<bool>> rows(size, vector<bool>(10)); |
| 10 | + vector<vector<bool>> cols(size, vector<bool>(10)); |
| 11 | + vector<vector<bool>> boxes(size, vector<bool>(10)); |
| 12 | + |
| 13 | + for (int i = 0; i < size; i++) { |
| 14 | + for (int j = 0; j < size; j++) { |
| 15 | + if (board[i][j] != '.') { |
| 16 | + int num = board[i][j] - '0'; |
| 17 | + int idx = i / 3 * 3 + j / 3; |
| 18 | + rows[i][num] = true; |
| 19 | + cols[j][num] = true; |
| 20 | + boxes[idx][num] = true; |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + dfs(board, 0, rows, cols, boxes); |
| 26 | + } |
| 27 | + |
| 28 | +private: |
| 29 | + bool valid(int num, int row, int col, int idx, vector<vector<bool>>& rows, |
| 30 | + vector<vector<bool>>& cols, vector<vector<bool>>& boxes) { |
| 31 | + return !rows[row][num] && !cols[col][num] && !boxes[idx][num]; |
| 32 | + } |
| 33 | + |
| 34 | + bool dfs(vector<vector<char>>& board, int size, vector<vector<bool>>& rows, |
| 35 | + vector<vector<bool>>& cols, vector<vector<bool>>& boxes) { |
| 36 | + if (size == 9 * 9) { |
| 37 | + return true; |
| 38 | + } else { |
| 39 | + bool ok = false; |
| 40 | + int row = size / 9; |
| 41 | + int col = size % 9; |
| 42 | + int idx = row / 3 * 3 + col / 3; |
| 43 | + if (board[row][col] == '.') { |
| 44 | + for (int i = 1; i <= 9; i++) { |
| 45 | + if (valid(i, row, col, idx, rows, cols, boxes)) { |
| 46 | + /* lock this grid as well as the number */ |
| 47 | + board[row][col] = i + '0'; |
| 48 | + rows[row][i] = true; |
| 49 | + cols[col][i] = true; |
| 50 | + boxes[idx][i] = true; |
| 51 | + ok = dfs(board, size + 1, rows, cols, boxes); |
| 52 | + if (!ok) { |
| 53 | + /* release this grid as well as the number */ |
| 54 | + rows[row][i] = false; |
| 55 | + cols[col][i] = false; |
| 56 | + boxes[idx][i] = false; |
| 57 | + board[row][col] = '.'; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } else { |
| 62 | + ok = dfs(board, size + 1, rows, cols, boxes); |
| 63 | + } |
| 64 | + return ok; |
| 65 | + } |
| 66 | + } |
| 67 | +}; |
0 commit comments