-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidSudoku.cpp
More file actions
88 lines (86 loc) · 2.27 KB
/
Copy pathvalidSudoku.cpp
File metadata and controls
88 lines (86 loc) · 2.27 KB
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
/**
* https://leetcode.com/problems/valid-sudoku/
* Array, Hash Table, Matrix
* Medium
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool checkRow(vector<vector<char> >& board, int row, int col) {
char num = board[row][col];
for (int i = 0; i < 9; i++) {
if (i == col) {
continue;
}
if (num == board[row][i]) {
return false;
}
}
return true;
}
bool checkCol(vector<vector<char> >& board, int row, int col) {
char num = board[row][col];
for (int i = 0; i < 9; i++) {
if (i == row) {
continue;
}
if (num == board[i][col]) {
return false;
}
}
return true;
}
bool checkBox(vector<vector<char> >& board, int row, int col) {
char num = board[row][col];
for (int i = (row / 3) * 3; i < (row / 3) * 3 + 3; i++) {
for (int j = (col / 3) * 3; j < (col / 3) * 3 + 3; j++) {
if (i == row && j == col) {
continue;
}
if (num == board[i][j]) {
return false;
}
}
}
return true;
}
bool checkAll(vector<vector<char> >& board, int row, int col) {
if (!checkRow(board, row, col) || !checkCol(board, row, col) || !checkBox(board, row, col)) {
cout << row << " " << col;
return false;
}
return true;
}
bool isValidSudoku(vector<vector<char> >& board) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
continue;
}
if (!checkAll(board, i, j)) {
return false;
}
}
}
return true;
}
};
int main() {
vector<vector<char> > board;
cout << "Input sudoku:" << endl;
char read;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cin >> read;
board[i][j] = read;
}
}
Solution solution;
if (solution.isValidSudoku(board)) {
cout << "is valid sudoku" << endl;
} else {
cout << "is not valid sudoku" << endl;
}
}