leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0037.cpp (1039B)
0 class Solution {
1 bool check(vector<vector<char>> &board, int i, int j, char val) {
2 for (int x = 0; x < 9; x++)
3 if (board[x][j] == val) return false;
4 for (int y = 0; y < 9; y++)
5 if (board[i][y] == val) return false;
7 i = (i / 3) * 3, j = (j / 3) * 3;
8 for (int x = i; x < i + 3; x++)
9 for (int y = j; y < j + 3; y++)
10 if (board[x][y] == val) return false;
11 return true;
12 }
13 bool solveSudoku(vector<vector<char>> &board, int i, int j) {
14 if (i == 9) return true;
15 if (j == 9) return solveSudoku(board, i + 1, 0);
16 if (board[i][j] != '.') return solveSudoku(board, i, j + 1);
18 for (char c = '1'; c <= '9'; c++) {
19 if (!check(board, i, j, c)) continue;
20 board[i][j] = c;
21 if (solveSudoku(board, i, j + 1)) return true;
22 board[i][j] = '.';
23 }
25 return false;
26 }
28 public:
29 void solveSudoku(vector<vector<char>> &board) { solveSudoku(board, 0, 0); }
30 };