NθUOθ#J⊖θ⊖θP0⊞υ⌕AKV#≔⁰ηWυ«≔⊟υι¿ι«⊞υι≔⊟ιιM✳⁻χ⊗ιPIι⊞υ⌕AKV#»«≧⁺¬∨∨ⅈⅉ№KA#η✳⁻⁶⊗KK#»»⎚Iη
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θ
Input n
.
UOθ#
Draw an n×n
square of #
s.
J⊖θ⊖θP0
Start at the bottom right corner. (Any digit works here, it's just a placeholder showing that the square has been visited.)
⊞υ⌕AKV#
Start with the possible moves from the corner. (This is empty for n=1
of course.)
≔⁰η
Start with 0
paths found.
Wυ«
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.
M✳⁻χ⊗ι
Move in that direction.
PIι
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.
⊞υ⌕AKV#
Push the available moves from this cell to the stack.
»«
Otherwise:
≧⁺¬∨∨ⅈⅉ№KA#η
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.
✳⁻⁶⊗KK#
Overwrite the current cell with a #
and move back to the previous cell.
»»⎚Iη
Clear the canvas and output the number of paths found.