Try it online! Link is to verbose version of code. Will do
n=5 on TIO but larger numbers are probably too slow. Explanation: Works by counting the paths from the bottom right corner back to the top left corner of an
n×n square drawn on the canvas.
n×n square of
Start at the bottom right corner. (Any digit works here, it's just a placeholder showing that the square has been visited.)
Start with the possible moves from the corner. (This is empty for
n=1 of course.)
0 paths found.
Repeat until all paths have been attempted.
Pop the remaining moves to try from the current cell from the stack.
If there are any moves left, then:
Push the moves back to the stack again.
Pop the next move to try.
Move in that direction.
Overwrite the current cell with the direction, so that we can find our way back, and also so that we don't try to re-enter the cell.
Push the available moves from this cell to the stack.
If the current cell is at the top left and there are no
#s left indicating that we've covered all of the squares, then increment the count of paths found.
Overwrite the current cell with a
# and move back to the previous cell.
Clear the canvas and output the number of paths found.