forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
91 lines (77 loc) · 2.34 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/// Source : https://leetcode.com/problems/valid-sudoku/
/// Author : liuyubobobo
/// Time : 2016-12-05
#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>
using namespace std;
/// Using hashtable to check every row, column and block.
/// Time Complexity: O(9*9)
/// Space Complexity: O(1)
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool hashtable[9][9];
// check for every row
memset(hashtable, 0, sizeof(hashtable));
for(int i = 0 ; i < 9 ; i ++)
for(int j = 0 ; j < 9 ; j ++)
if(board[i][j] != '.'){
int num = board[i][j] - '0' - 1;
if(hashtable[i][num] == 1)
return false;
hashtable[i][num] = 1;
}
// check for every col
memset(hashtable, 0, sizeof(hashtable));
for(int i = 0 ; i < 9 ; i ++)
for(int j = 0 ; j < 9 ; j ++)
if(board[j][i] != '.'){
int num = board[j][i] - '0' - 1;
if( hashtable[i][num] == 1 )
return false;
hashtable[i][num] = 1;
}
// check for every block
memset(hashtable, 0, sizeof(hashtable));
for(int i = 0 ; i < 9 ; i ++){
int br = i/3;
int bc = i%3;
for(int ii = 0 ; ii < 3 ; ii ++)
for(int jj = 0 ; jj < 3 ; jj ++){
int r = br*3 + ii;
int c = bc*3 + jj;
if(board[r][c] != '.'){
int num = board[r][c] - '0' - 1;
if (hashtable[i][num] == 1)
return false;
hashtable[i][num] = 1;
}
}
}
return true;
}
};
int main() {
vector<string> input = {
"53..7....",
"6..195...",
".98....6.",
"8...6...3",
"4..8.3..1",
"7...2...6",
".6....28.",
"...419..5",
"....8..79"
};
vector<vector<char>> board;
for(const string& row: input){
vector<char> r;
for(char c: row)
r.push_back(c);
board.push_back(r);
}
cout << Solution().isValidSudoku(board) << endl;
return 0;
}