diff --git a/include/s0036_valid_sudoku.hpp b/include/s0036_valid_sudoku.hpp new file mode 100644 index 0000000..73df99d --- /dev/null +++ b/include/s0036_valid_sudoku.hpp @@ -0,0 +1,15 @@ +#ifndef S0036_VALID_SUDOKU_HPP +#define S0036_VALID_SUDOKU_HPP + +#include +#include +#include + +using namespace std; + +class Solution { + public: + bool isValidSudoku(vector>& board); +}; + +#endif diff --git a/src/s0036_valid_sudoku.cpp b/src/s0036_valid_sudoku.cpp new file mode 100644 index 0000000..4c6855b --- /dev/null +++ b/src/s0036_valid_sudoku.cpp @@ -0,0 +1,38 @@ +#include "s0036_valid_sudoku.hpp" + +bool Solution::isValidSudoku(vector>& board) { + vector> rows; + vector> columns; + vector> grids; + // Initialize vectors + for (int i{0}; i < 9; ++i) { + rows.push_back(unordered_map{}); + columns.push_back(unordered_map{}); + grids.push_back(unordered_map{}); + } + for (int i{0}; i < 9; ++i) { + for (int j{0}; j < 9; ++j) { + if (board[i][j] == '.') { + continue; + } + if (rows[j].count(board[i][j]) == 1) { + return false; + } else { + rows[j][board[i][j]] = 1; + } + if (columns[i].count(board[i][j]) == 1) { + return false; + } else { + columns[i][board[i][j]] = 1; + } + int gridIndex = + static_cast(floor(j / 3)) + 3 * static_cast(floor(i / 3)); + if (grids[gridIndex].count(board[i][j]) == 1) { + return false; + } else { + grids[gridIndex][board[i][j]] = 1; + } + } + } + return true; +} diff --git a/tests/s0036_valid_sudoku.cpp b/tests/s0036_valid_sudoku.cpp new file mode 100644 index 0000000..614afb7 --- /dev/null +++ b/tests/s0036_valid_sudoku.cpp @@ -0,0 +1,33 @@ +#include "s0036_valid_sudoku.hpp" + +#include + +TEST(Problem36, Case1) { + vector> board{{'5', '3', '.', '.', '7', '.', '.', '.', '.'}, + {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, + {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, + {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, + {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, + {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, + {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, + {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, + {'.', '.', '.', '.', '8', '.', '.', '7', '9'}}; + bool o{true}; + Solution solution; + EXPECT_EQ(solution.isValidSudoku(board), o); +} + +TEST(Problem36, Case2) { + vector> board{{'8', '3', '.', '.', '7', '.', '.', '.', '.'}, + {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, + {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, + {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, + {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, + {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, + {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, + {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, + {'.', '.', '.', '.', '8', '.', '.', '7', '9'}}; + bool o{false}; + Solution solution; + EXPECT_EQ(solution.isValidSudoku(board), o); +}