First a note: Sorry that my images aren’t separated. I’m a new member, so I don’t have enough reputation points to post more than a single hyperlink.
Let M be an n by n array (mathematically square matrix) of characters.
In M, I need to be able to find all permutation of characters with a restriction. The permutations do not have to be linear, but they they must contain characters such that each character is adjacent to at least one other character in the permutation. An example of an acceptable permutation follows below:
An unacceptable permutation is shown below.
I have derived this much:
- A permutation can have at most n squared characters in it (as no characters can be repeated).
- I do not know the exact number of permutation given the restrictions, but I believe there can be no more than the value generated by evaluating the expression pictured in the hyperlink.
I can very easily find the permutations which only contain characters in straight lines: vertical lines, horizontal lines, and diagonals. I am not sure of a way to exhaustively find all remaining permutations.
I have done research and have not been able to find a solution to a similar problem.
Any advice in the development of such an exhaustive algorithm would be greatly appreciated.
One algorithm comes to mind immediately, though optimizations can be made, if time-complexity is a concern.
At each element in the 2×2 array (or we can call it a matrix if you like), there are 8 directions that we can travel (North, NE, East, SE, South, SW, West, NW).
The pseudo code for the meat of the algorithm goes a bit like this (I assume pass by value, so that “current_string” is a new string at each function call):
Now you need to add some checks for things like “is position + direction outside the bounds of the array, if so, print current_string and terminate”.
The high level idea of the algorithm above is to search along all possible paths recursively, terminating paths when they run into themselves (in the same way that snakes die in the game Snake).
If you use hashing to test containment of a new letter against the current string (as per the line
if(!current_string.Contains(new_letter)){), which is amortized O(1) searching, then the worst case runtime complexity of this algorithm is linear in the number of possible strings there are in the matrix. I.e. if there are n possible string combonations in the matrix, then this algorithm takes about cn steps to complete for large n, where c is some constant.