diff --git a/Sudoko Solver b/Sudoko Solver new file mode 100644 index 0000000..c8d4dd1 --- /dev/null +++ b/Sudoko Solver @@ -0,0 +1,78 @@ +#BACKTRACKING ALGORITHM + + +board=[[3, 0, 6, 5, 0, 8, 4, 0, 0], + [5, 2, 0, 0, 0, 0, 0, 0, 0], + [0, 8, 7, 0, 0, 0, 0, 3, 1], + [0, 0, 3, 0, 1, 0, 0, 8, 0], + [9, 0, 0, 8, 6, 3, 0, 0, 5], + [0, 5, 0, 0, 9, 0, 6, 0, 0], + [1, 3, 0, 0, 0, 0, 2, 5, 0], + [0, 0, 0, 0, 0, 0, 0, 7, 4], + [0, 0, 5, 2, 0, 6, 3, 0, 0]] + +def display_sudoko(bo): + for i in range(len(bo)): + if i % 3 == 0 and i!= 0: + print("-----------------------------") + for j in range(len(bo)): + if j%3==0 and j!=0: + print("|",end=" ") + print(bo[i][j],end=" ") + print() + print() + +def find_empty(bo): + for i in range(len(bo)): + for j in range(len(bo[0])): + if bo[i][j] == 0: + return (i, j) # row, col + + + +def valid(bo, num, pos): + # Check row + for i in range(len(bo[0])): + if bo[pos[0]][i] == num : + return False + + # Check column + for i in range(len(bo)): + if bo[i][pos[1]] == num : + return False + + # Check box + box_x = pos[1] // 3 + box_y = pos[0] // 3 + + for i in range(box_y*3, box_y*3 + 3): + for j in range(box_x * 3, box_x*3 + 3): + if bo[i][j] == num and (i,j) != pos: + return False + + return True + +def solve(bo): + find = find_empty(bo) + if not find: + return True + else: + row, col = find + + for i in range(1,10): + if valid(bo, i, (row, col)): #row,col goes inside pos + bo[row][col] = i + + if solve(bo): + return True + else: + bo[row][col] = 0 + + + + + +display_sudoko(board) +print() +solve(board) +display_sudoko(board)