Skip to content

Commit c69dc21

Browse files
authored
Create Day-20_Valid_Sudoku.py
1 parent c40f1f6 commit c69dc21

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# My Solution - O(N^2)
2+
class Solution:
3+
def isValidSudoku(self, board: List[List[str]]) -> bool:
4+
rows, cols = 9, 9
5+
# Check the Rows
6+
for i in range(rows):
7+
s = set()
8+
for j in range(cols):
9+
if board[i][j] in s and board[i][j] != '.':
10+
return False
11+
s.add(board[i][j])
12+
13+
# Check the Cols
14+
for i in range(cols):
15+
s = set()
16+
for j in range(rows):
17+
if board[j][i] in s and board[j][i] != '.':
18+
return False
19+
s.add(board[j][i])
20+
21+
# Check the Submatrices
22+
for i in range(0,9,3):
23+
for j in range(9):
24+
if j%3 == 0:
25+
ss = set()
26+
for el in board[j][i:i+3]:
27+
if el != '.' and el in ss:
28+
return False
29+
else:
30+
ss.add(el)
31+
return True
32+
33+
34+
# A Better approach
35+
class Solution:
36+
def isValidSudoku(self, board: List[List[str]]) -> bool:
37+
seen = {}
38+
for row in range(9):
39+
for col in range(9):
40+
val = board[row][col]
41+
if val == '.':
42+
continue
43+
if (val,'r',row) in seen:
44+
return False
45+
if (val,'c',col) in seen:
46+
return False
47+
if (val,row//3,col//3) in seen:
48+
return False
49+
seen[(val,'r',row)] =True
50+
seen[(val,'c',col)]=True
51+
seen[(val,row//3,col//3)]=True
52+
return True

0 commit comments

Comments
 (0)