From d5c38b979f41d08f438562a0cead577214173218 Mon Sep 17 00:00:00 2001 From: juan Date: Wed, 29 Jun 2022 09:05:26 +0800 Subject: [PATCH] vault backup: 2022-06-29 09:05:26 --- CS notes/pages/Leetcode Valid-Sudoku.md | 67 +++++++++++++++++-------- 1 file changed, 45 insertions(+), 22 deletions(-) diff --git a/CS notes/pages/Leetcode Valid-Sudoku.md b/CS notes/pages/Leetcode Valid-Sudoku.md index aa19683..66a5a4e 100644 --- a/CS notes/pages/Leetcode Valid-Sudoku.md +++ b/CS notes/pages/Leetcode Valid-Sudoku.md @@ -77,7 +77,52 @@ This should be a follow-up of [[Leetcode Reshape-The-Matrix]], I tried to implem Besides overthinking, I also spent a lot of time learning how to use sets and init multi-dimensional vectors. +**Take TWO:** +Use a hash table to store whether an element is present: +```cpp +int usedRow[9][10] = {}; +int usedCol[9][10] = {}; +int usedGrid[9][10] = {}; +``` ### Solution + +My new solution using hash map +```cpp +class Solution { +public: + bool isValidSudoku(vector> &board) { + // from 0 to 9 + int usedRow[9][10] = {}; + int usedCol[9][10] = {}; + int usedGrid[9][10] = {}; + int grid; + int boardVal; + + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + grid = i / 3 * 3 + j / 3; + + boardVal = board[i][j]; + if (boardVal == '.') { + continue; + } + boardVal = boardVal - '0'; + + if (usedRow[i][boardVal] || usedCol[j][boardVal] || + usedGrid[grid][boardVal]) { + return false; + } + usedRow[i][boardVal]++; + usedCol[j][boardVal]++; + usedGrid[grid][boardVal]++; + } + } + + return true; + } +}; +``` + Bad solution :( ```cpp class Solution { @@ -186,25 +231,3 @@ public: }; ``` - -Others' using array. -```cpp -class Solution { -public: - bool isValidSudoku(vector> &board) { - int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0}; - - for (int i = 0; i < board.size(); ++i) - for (int j = 0; j < board[i].size(); ++j) - if (board[i][j] != '.') { - int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3; - if (used1[i][num] || used2[j][num] || used3[k][num]) - return false; - used1[i][num] = used2[j][num] = used3[k][num] = 1; - } - - return true; - } -}; - -``` \ No newline at end of file