Skip to content

Sudoku Validator in Python #105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions GeeksforGeeks/vaildsudoku.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#valid sudoku by anshika gupta

#check if row is valid
def validrow(arr,row):
s=set()
for i in range(9):
if arr[row][i] in s:
return False
if arr[row][i] !='.':
s.add(arr[row][i])
return(True)

#check if the column is valid
def validcol(arr,col):
s=set()
for j in range(9):
if arr[j][col] in s:
return False
if arr[j][col]!='.':
s.add(arr[j][col])

return(True)

#check if the 3x3 box is valid
def validbox(arr,row,col):
s=set()
for i in range(3):
for j in range(3):
if arr[i+row][j+col] in s:
return False
if arr[i+row][j+col] !='.':
s.add(arr[i+row][j+col])

return(True)


def check_validity(arr,row,col):
return(validrow(arr,row) and validcol(arr,col) and validbox(arr,row - row%3,col-col%3))

def sudoku(arr):
for i in range(0,len(arr)):
for j in range(0,len(arr)):
if not check_validity(arr,i,j):
return(False)
return(True)

# n=int(input("enter order of the matrix"))
matrix=[[ '5', '3', '.', '.', '7', '.', '.', '.', '.' ],
[ '6', '.', '.', '1', '9', '5', '.', '.', '.' ],
[ '.', '9', '8', '.', '.', '.', '.', '6', '.' ],
[ '8', '.', '.', '.', '6', '.', '.', '.', '3' ],
[ '4', '.', '.', '8', '.', '3', '.', '.', '1' ],
[ '7', '.', '.', '.', '2', '.', '.', '.', '6' ],
[ '.', '6', '.', '.', '.', '.', '2', '8', '.' ],
[ '.', '.', '.', '4', '1', '9', '.', '.', '5' ],
[ '.', '.', '.', '.', '8', '.', '.', '7', '9' ]]
if sudoku(matrix)==True:
print("Valid")
else:
print("Invalid")