Skip to content

Commit ba2df2f

Browse files
[Neetcode] Valid sudoku
1 parent a142098 commit ba2df2f

2 files changed

Lines changed: 74 additions & 0 deletions

File tree

Neetcode/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ set(CMAKE_CXX_STANDARD 17)
66
add_executable(Two_sum_neetcode "Two sum/Two sum.cpp")
77
add_executable(Group_anagrams_neetcode "Group anagrams/Group anagrams.cpp")
88
add_executable(Top_K_Frequent_Elements "Top K Frequent Elements/Top K Frequent Elements.cpp")
9+
add_executable(Valid_sudoku_neetcode "Valid sudoku/Valid sudoku.cpp")
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#include <bitset>
2+
#include <iostream>
3+
#include <vector>
4+
5+
class Solution {
6+
public:
7+
bool isValidSudoku(std::vector<std::vector<char>> &board);
8+
9+
private:
10+
static bool validateElement(std::bitset<9> &validity, char element);
11+
};
12+
13+
bool Solution::isValidSudoku(std::vector<std::vector<char>> &board) {
14+
std::bitset<9> row_validity, col_validity, box_validity;
15+
16+
for (std::size_t i = 0; i < board.size(); ++i) {
17+
row_validity.reset();
18+
col_validity.reset();
19+
for (std::size_t j = 0; j < board[i].size(); ++j) {
20+
if (!validateElement(row_validity, board[i][j])) {
21+
return false;
22+
}
23+
if (!validateElement(col_validity, board[j][i])) {
24+
return false;
25+
}
26+
}
27+
}
28+
29+
for (std::size_t i_box_row = 0; i_box_row < board.size(); i_box_row += 3) {
30+
for (std::size_t j_box_row = 0; j_box_row < board.size(); j_box_row += 3) {
31+
box_validity.reset();
32+
for (std::size_t i = i_box_row; i < i_box_row + 3; ++i) {
33+
for (std::size_t j = j_box_row; j < j_box_row + 3; ++j) {
34+
if (!validateElement(box_validity, board[i][j])) {
35+
return false;
36+
}
37+
}
38+
}
39+
}
40+
}
41+
42+
return true;
43+
}
44+
45+
bool Solution::validateElement(std::bitset<9> &validity, const char element) {
46+
if (element == '.') {
47+
return true;
48+
}
49+
50+
const auto num = element - '1';
51+
if (validity.test(num)) {
52+
return false;
53+
}
54+
55+
validity.set(num);
56+
return true;
57+
}
58+
59+
int main(int argc, char *argv[]) {
60+
std::vector<std::vector<char>> board{
61+
{'1', '2', '.', '.', '3', '.', '.', '.', '.'},
62+
{'4', '.', '.', '5', '.', '.', '.', '.', '.'},
63+
{'.', '9', '1', '.', '.', '.', '.', '.', '3'},
64+
{'5', '.', '.', '.', '6', '.', '.', '.', '4'},
65+
{'.', '.', '.', '8', '.', '3', '.', '.', '5'},
66+
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
67+
{'.', '.', '.', '.', '.', '.', '2', '.', '.'},
68+
{'.', '.', '.', '4', '1', '9', '.', '.', '8'},
69+
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
70+
71+
std::cout << Solution().isValidSudoku(board) << std::endl;
72+
return 0;
73+
}

0 commit comments

Comments
 (0)