A self-avoiding walk is a path from one point to another that never intersects itself. Such paths are usually considered to occur on lattices, so that steps are only allowed in a discrete number of directions and of certain lengths. Wolfram Mathworld
Written in python (3.7.6), using pygame library (2.0.1)
💡 Press SPACE if you want to create another self-avoiding path or if you want to pause the program.
I have commented each file as best as I can, so If you want to know more about how each version of my self-avoiding walk works check the python files and read the comments. Now I'm gonna briefly explain the main differences between the versions here.
The program chooses the first spot randomly, but then I found out that sometimes it is impossible to create a self-avoiding path. If the number of rows and columns of the grid are odd numbers, and one of the x-coordinate or y-coordinate of the first point is an even number and the other one is an odd number, then it is impossible to create a self-avoiding path.
- The length of a path is equal to the number of rows time the number of columns minus 1 (row x cols - 1), so for a 3 by 3 grid the length of a self-avoiding path would be 8. You can also conclude that the length of the s-a path will be even for a grid with an odd number of rows and cols.
- Every step you take on the grid, you either step on an even/black cell from an odd/white cell or vise versa. Therefore your second step will be on a cell with the same color as the cell you started.
Based on these statements (1, 2) in an odd by odd grid if you start on a white cell you will end up on a white cell after getting to the end of your self-avoiding walk and you should end up on a black cell if you start on a black cell, but there is a problem. in an odd by odd grid, the number of black/even cells is always one less than the number of white/odd cells.** Ss stated before the length of the path is n x m - 1, so if you start on a black cell and finish on a black cell it means that you have stepped on ((n x m - 1) / 2) + 1 = (n x m + 1) / 2 = (3 x 3 + 1) / 2 = 5 black cells but there are only (n x m - 1) / 2 = (3 x 3 - 1) / 2 = 4 black cells. So, it is impossible to start on a black cell and finish on a black cell. Therefore, it is impossible to create a self-avoiding path that starts on a black cell(in an (odd x odd) grid).
**
For a (n x m) gird (which n and m are odd numbers)
the number of black cells is equal to (n x m - 1) / 2
the number of white cells is equal to (n x m + 1) / 2