
If both rowOk and columnOk are True then the lines 6–10 check if the entry fits a certain block. columnOk: this one makes sure if there are no repeating numbers in the j-th column. rowOk: this one checks if there are no repeating numbers in the i-th row. def isValid(sudoku, i, j, e): rowOk = all( for x in range(9)]) if rowOk: columnOk = all( for x in range(9)]) if columnOk: secTopX, secTopY = 3*(i//3), 3*(j//3) for x in range(secTopX, secTopX+3): for y in range(secTopY, secTopY+3): if sudoku = e: return False return True return False Otherwise, the function will return False. The following function returns True if none of the three rules are violated. We need a function that checks whether it violates the three main rules of sudoku when placed to the i-th row and j-th column. Whenever it encounters an empty cell, the function returns the corresponding indexes. This iterates through all the columns in the first row, then second row and so on. def findNextCellToFill(sudoku): for x in range(9): for y in range(9): if sudoku = 0: return x, y return -1, -1 To solve a certain cell, we must first find the row and column number of a cell that’s empty. Yet, it’s licensed as Creative Commons BY-NC-SA which gives me a green light for sharing. The idea and implementation were copied from MIT OpenCourseWare Youtube channel, more specifically from this video. Let’s get to it! Now we are ready for a step-by-step algorithm-creation.ĭisclaimer: I did not create this sudoku-solving algorithm entirely myself. def printsudoku(): print("\n\n\n\n\n") for i in range(len(sudoku)): line = "" if i = 3 or i = 6: print("-") for j in range(len(sudoku)): if j = 3 or j = 6: line += "| " line += str(sudoku)+" " print(line)Īn example output of a printsudoku function Correct sudoku example code#
Below is the code example along with its output. Hence, it would be great to print out the current state of the puzzle. Sure, this two-dimensional python array does not look like real sudoku without any gridlines. When trying to access a certain element from the i-th row and j-th column, you simply need to call sudoku Making it look a lot more like a real sudoku We should obtain the following: sudoku =, ,, ,, ,, , ]
I propose that we handle this puzzle as a two-dimensional Python array where empty boxes are represented with zeros and other boxes with corresponding numbers. Let’s take a random sudoku puzzle from the Internet and try to solve it with Python.