Algorithm for solving Knights Tour with Python(revisited)

The original Algorithm For Knights Tour was a pretty popular post, so I decided to revisit it thanks to an interesting email I got. This implementation has a couple changes:

  • You can define a ruleset for locations the knight must be at any given move
  • You can define whether the path needs to be closed or not (Knight returns to starting position)
  • There’s a visualizer now! (You’ll need to have pygame installed for it to work though)
  • No more ugly exiting using sys.exit(), we catch custom exceptions this time around

Here’s what the visualizer looks like:
(pink because pink is the best color obvs)

tour.py

The tour code is mainly the same as the original post, but with the added custom exception class and booleans. Lines 137-146 deal with obeying to a custom tour ruleset 

tour_visualizer.py

The visualizer only works if you have pygame installed. It basically runs at the end of tour.py and does a cool graphic. Completely extraneous, but I wanted something a bit more substantial than a printed out tour at the end of the program. 😛

This was pretty fun to revisit! I’m feeling all fired up and ready to tackle some other interesting problem.

-Sophie

Leave a Reply

Your email address will not be published. Required fields are marked *