1+ #include < bits/stdc++.h>
2+ using namespace std ;
3+
4+ bool checkColumns (vector<vector<char >> &board)
5+ {
6+ unordered_map<char , int > umap;
7+ for (int i = 0 ; i < 9 ; i++)
8+ {
9+ for (int j = 0 ; j < 9 ; j++)
10+ {
11+ if (umap[board[j][i]] == 0 )
12+ {
13+ umap[board[j][i]]++;
14+ }
15+ else if (umap[board[j][i]] > 0 )
16+ {
17+
18+ if (board[j][i] != ' .' )
19+ {
20+ return false ;
21+ }
22+ }
23+ }
24+
25+ umap.clear ();
26+ }
27+
28+ return true ;
29+ }
30+
31+ bool checkRows (vector<vector<char >> &board)
32+ {
33+ unordered_map<char , int > umap;
34+ for (int i = 0 ; i < 9 ; i++)
35+ {
36+ for (int j = 0 ; j < 9 ; j++)
37+ {
38+ if (umap[board[i][j]] == 0 )
39+ {
40+ umap[board[i][j]]++;
41+ }
42+ else if (umap[board[i][j]] > 0 )
43+ {
44+
45+ if (board[i][j] != ' .' )
46+ {
47+ return false ;
48+ }
49+ }
50+ }
51+
52+ umap.clear ();
53+ }
54+
55+ return true ;
56+ }
57+
58+ bool helperMatrixChecker (vector<vector<char >> &board, int p, int q)
59+ {
60+ unordered_map<char , int > umap;
61+ for (int i = 0 ; i < 3 ; i++)
62+ {
63+ for (int j = 0 ; j < 3 ; j++)
64+ {
65+ // cout<<board[p+i][q+j]<<" ";
66+ if (board[p + i][q + j] != ' .' && umap[board[p + i][q + j]] > 0 )
67+ {
68+ return false ;
69+ }
70+ else if (umap[board[p + i][q + j]] == 0 )
71+ {
72+ umap[board[p + i][q + j]]++;
73+ }
74+ }
75+ // cout<<endl;
76+ }
77+
78+ return true ;
79+ }
80+
81+ bool checkMatrix (vector<vector<char >> &board)
82+ {
83+ for (int i = 0 ; i < 9 ; i += 3 )
84+ {
85+ for (int j = 0 ; j < 9 ; j += 3 )
86+ {
87+ // 0 0 //0 3 //0 6
88+ // 3 0 //3 3 //3 6
89+ // 6 0 //6 3 //6 6
90+
91+ if (helperMatrixChecker (board, i, j) == false )
92+ {
93+ return false ;
94+ }
95+ }
96+ }
97+
98+ return true ;
99+ }
100+ bool isValidSudoku (vector<vector<char >> &board)
101+ {
102+
103+ return checkColumns (board) && checkRows (board) && checkMatrix (board);
104+ }
105+
106+ int main ()
107+ {
108+
109+ vector<vector<char >> test = {
110+ {' 8' , ' 3' , ' .' , ' .' , ' 7' , ' .' , ' .' , ' .' , ' .' },
111+ {' 6' , ' .' , ' .' , ' 1' , ' 9' , ' 5' , ' .' , ' .' , ' .' },
112+ {' .' , ' 9' , ' 8' , ' .' , ' .' , ' .' , ' .' , ' 6' , ' .' },
113+ {' 8' , ' .' , ' .' , ' .' , ' 6' , ' .' , ' .' , ' .' , ' 3' },
114+ {' 4' , ' .' , ' .' , ' 8' , ' .' , ' 3' , ' .' , ' .' , ' 1' },
115+ {' 7' , ' .' , ' .' , ' .' , ' 2' , ' .' , ' .' , ' .' , ' 6' },
116+ {' .' , ' 6' , ' .' , ' .' , ' .' , ' .' , ' 2' , ' 8' , ' .' },
117+ {' .' , ' .' , ' .' , ' 4' , ' 1' , ' 9' , ' .' , ' .' , ' 5' },
118+ {' .' , ' .' , ' .' , ' .' , ' 8' , ' .' , ' .' , ' 7' , ' 9' }
119+ };
120+
121+ cout << isValidSudoku (test) << endl;
122+ }
0 commit comments