Aia Exp-2 Vu22eece0100102
Aia Exp-2 Vu22eece0100102
Ram Prasad
VU22EECE0100102
AIA lab Observation
Experiment - 2
SUDOKU SOLVER
1. 9x9 Sudoku Solver
M = 9
def puzzle(a):
for i in range(M):
for j in range(M):
print(a[i][j],end =" ")
print()
def solve(grid,row,col,num):
for x in range(9):
if grid[row][x] == num:
return False
for x in range(9):
if grid[x][col] == num:
return False
startRow = row - row %3
startCol = col - col %3
for i in range(3):
for j in range(3):
if grid[i + startRow][j + startCol] == num:
return False
return True
else:
print("Solution does not exist:(")
RESULT:
CASE 1: SOLUTION DOESN’T EXIST
The input puzzle is:
[1, 5, 0, 0, 3, 0, 9, 0, 2]
[0, 1, 0, 0, 0, 4, 0, 0, 0]
[4, 0, 7, 0, 0, 0, 2, 0, 8]
[0, 0, 5, 2, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 9, 8, 1, 0, 0]
[0, 4, 0, 0, 0, 3, 0, 0, 0]
[0, 0, 0, 3, 6, 0, 0, 7, 5]
[0, 7, 0, 0, 0, 0, 0, 0, 3]
[9, 0, 3, 0, 0, 0, 6, 0, 4]
[0, 0, 0, 2, 6, 0, 7, 0, 1]
[6, 8, 0, 0, 7, 0, 0, 9, 0]
[1, 9, 0, 0, 0, 4, 5, 0, 0]
[8, 2, 0, 1, 0, 0, 0, 4, 0]
[0, 0, 4, 6, 0, 2, 9, 0, 0]
[0, 5, 0, 0, 0, 3, 0, 2, 8]
[0, 0, 9, 3, 0, 0, 0, 7, 4]
[0, 4, 0, 0, 5, 0, 0, 3, 6]
[7, 0, 3, 0, 1, 8, 0, 0, 0]
def puzzle(a):
for i in range(M):
for j in range(M):
for x in range(M):
if grid[row][x] == num:
return False
for x in range(M):
if grid[x][col] == num:
return False
region = [
(0, 0, 0, 1, 1),
(0, 1, 2, 2, 3),
(1, 2, 3, 4, 4)
startRow = row // 3
startCol = col // 3
for i in range(3):
for j in range(3):
regionRow = region[startRow][i]
regionCol = region[startCol][j]
if grid[regionRow][regionCol] == num:
return False
return True
return True
if col == M:
row += 1
col = 0
if grid[row][col] > 0:
grid[row][col] = num
return True
grid[row][col] = 0
return False
grid = [
[0, 0, 0, 2, 0],
[0, 0, 0, 0, 3],
[0, 0, 0, 1, 0],
[0, 3, 0, 0, 0],
[2, 0, 0, 0, 0]
for i in grid:
print(i)
print("\n")
if (Suduko(grid, 0, 0)):
print("The Solution is given below: ")
puzzle(grid)
print("\n")
else:
[0, 0, 0, 2, 0]
[0, 0, 0, 0, 3]
[0, 0, 0, 1, 0]
[0, 3, 0, 0, 0]
[2, 0, 0, 0, 0]