|
1 | 1 | //go:build ignore
|
2 | 2 | #include "cpp/common/Solution.h"
|
3 | 3 |
|
4 |
| - |
5 | 4 | using namespace std;
|
6 | 5 | using json = nlohmann::json;
|
7 | 6 |
|
| 7 | +constexpr int N = 9; |
| 8 | + |
8 | 9 | class Solution {
|
9 | 10 | public:
|
10 |
| - bool isValidSudoku(vector<vector<char>>& board) { |
11 |
| - |
| 11 | + bool isValidSudoku(const vector<vector<char>> &board) { |
| 12 | + for (int i = 0; i < N; ++i) { |
| 13 | + int r = 0, c = 0, b = 0; |
| 14 | + for (int j = 0; j < N; ++j) { |
| 15 | + if (board[i][j] != '.') { |
| 16 | + int v = 1 << (board[i][j] - '1'); |
| 17 | + if (r & v) |
| 18 | + return false; |
| 19 | + r |= v; |
| 20 | + } |
| 21 | + if (board[j][i] != '.') { |
| 22 | + int v = 1 << (board[j][i] - '1'); |
| 23 | + if (c & v) |
| 24 | + return false; |
| 25 | + c |= v; |
| 26 | + } |
| 27 | + int bi = (i / 3) * 3 + j / 3; |
| 28 | + int bj = (i % 3) * 3 + j % 3; |
| 29 | + if (board[bi][bj] != '.') { |
| 30 | + int v = 1 << (board[bi][bj] - '1'); |
| 31 | + if (b & v) |
| 32 | + return false; |
| 33 | + b |= v; |
| 34 | + } |
| 35 | + } |
12 | 36 | }
|
| 37 | + return true; |
| 38 | + } |
13 | 39 | };
|
14 | 40 |
|
15 | 41 | json leetcode::qubh::Solve(string input_json_values) {
|
16 |
| - vector<string> inputArray; |
17 |
| - size_t pos = input_json_values.find('\n'); |
18 |
| - while (pos != string::npos) { |
19 |
| - inputArray.push_back(input_json_values.substr(0, pos)); |
20 |
| - input_json_values = input_json_values.substr(pos + 1); |
21 |
| - pos = input_json_values.find('\n'); |
22 |
| - } |
23 |
| - inputArray.push_back(input_json_values); |
| 42 | + vector<string> inputArray; |
| 43 | + size_t pos = input_json_values.find('\n'); |
| 44 | + while (pos != string::npos) { |
| 45 | + inputArray.push_back(input_json_values.substr(0, pos)); |
| 46 | + input_json_values = input_json_values.substr(pos + 1); |
| 47 | + pos = input_json_values.find('\n'); |
| 48 | + } |
| 49 | + inputArray.push_back(input_json_values); |
24 | 50 |
|
25 |
| - Solution solution; |
26 |
| - vector<vector<string>> board_str = json::parse(inputArray.at(0)); |
27 |
| - auto board = vector<vector<char>>(board_str.size(), vector<char>(board_str[0].size())); |
28 |
| - for (size_t i = 0; i < board.size(); ++i) { |
29 |
| - for (size_t j = 0; j < board[i].size(); ++j) { |
30 |
| - board[i][j] = board_str[i][j][0]; |
31 |
| - } |
32 |
| - } |
33 |
| - return solution.isValidSudoku(board); |
| 51 | + Solution solution; |
| 52 | + vector<vector<string>> board_str = json::parse(inputArray.at(0)); |
| 53 | + auto board = |
| 54 | + vector<vector<char>>(board_str.size(), vector<char>(board_str[0].size())); |
| 55 | + for (size_t i = 0; i < board.size(); ++i) { |
| 56 | + for (size_t j = 0; j < board[i].size(); ++j) { |
| 57 | + board[i][j] = board_str[i][j][0]; |
| 58 | + } |
| 59 | + } |
| 60 | + return solution.isValidSudoku(board); |
34 | 61 | }
|
0 commit comments