I am having trouble figuring out how to read from a text file for my Sudoku solver. So I can get it to read the board from a text file, and I can get my code to solve the board when it's in the code, but I can't bet them to read and solve together. This is what I have and I've tried a few methods to get it to possibly work, but I'm not understanding it. If anyone could help, I'd really appreciate it! Thanks!
board = []
with open('project.txt','r') as file:
for line in file:
board.append(line.strip('\n').split(','))
if line != '':
(board)
#backtracking
def solve(pr):
find = find_empty(pr)
if not find:
return True
else:
row, col = find
for r in range(1,10):
if valid(pr, r, (row, col)):
pr[row][col] = r
if solve(pr):
return True
pr[row][col] = 0
return False
def valid(pr, num, pos):
# Check row
for r in range(len(pr[0])):
if pr[pos[0]][r] == num and pos[1] != r:
return False
# Check column
for r in range(len(pr)):
if pr[r][pos[1]] == num and pos[0] != r:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for r in range(box_y*3, box_y*3 + 3):
for c in range(box_x * 3, box_x*3 + 3):
if pr[r][c] == num and (r,c) != pos:
return False
return True
#formatting
def print_board(pr):
for r in range(len(pr)):
if r % 3 == 0 and r != 0:
print("- - - - - - - - - - - - - ")
for c in range(len(pr[0])):
if c % 3 == 0 and c != 0:
print(" | ", end="")
if c == 8:
print(pr[r][c])
else:
print(str(pr[r][c]) + " ", end="")
def find_empty(pr):
for r in range(len(pr)):
for c in range(len(pr[0])):
if pr[r][c] == 0:
return (r, c) # row, col
return None
solve(board)
print_board(board)
my txt file looks like this:
003020600
900305001
001806400
008102900
700000008
006708200
002609500
800203009
005010300