vault backup: 2022-06-29 09:05:26
This commit is contained in:
parent
72332f9b82
commit
d5c38b979f
|
@ -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.
|
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
|
### Solution
|
||||||
|
|
||||||
|
My new solution using hash map
|
||||||
|
```cpp
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool isValidSudoku(vector<vector<char>> &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 :(
|
Bad solution :(
|
||||||
```cpp
|
```cpp
|
||||||
class Solution {
|
class Solution {
|
||||||
|
@ -186,25 +231,3 @@ public:
|
||||||
};
|
};
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Others' using array.
|
|
||||||
```cpp
|
|
||||||
class Solution {
|
|
||||||
public:
|
|
||||||
bool isValidSudoku(vector<vector<char>> &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;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
```
|
|
Loading…
Reference in a new issue