Imagine we have a snake contained in a matrix that is matrix[a][b]: it is a tall and b wide. Cells in the matrix can be considered neighbors if they are directly, above, below, or to the left or right of another cell. Diagonal cells are not neighbors. The snake within the matrix must be continuous and its length is calculated by the number of cells it occupies. The snake is 1 cell wide and it can occupy any cells within the matrix but cannot leave the matrix. The snake can make 90 degree turns within the matrix but it cannot touch itself. What this means is that each cell within the snake must have exactly two neighbors, while the head the tail must have only 1 neighbor.
In the example, the snake is in a blue, 3 by 9 matrix.
An invalid snake would look like this: The red circle highlights the location that the snake touches itself.
A valid snake would look like this:
This snake is 19 cells long.
The snake doesn't need to start on the corners. In some cases, it results in a longer snake:
This snake is 20 cells long.
The question is, what is length of a longest snake found within any given matrix[a][b]? Is there an graph traversal algorithm to find the length? Can we find the length using a formula without traversing through the graph?
We tried to brute force this problem but it seems like the solution is inefficient. We are interested in whether there is a mathematical formula or a known algorithm to solve this problem. Any links to papers or articles on this topic would be helpful!



I haven't thoroughly searched the internet (example article after quick scan; other article). So I can't tell if there is a widely known algorithm for this question.
The following MiniZinc constraint programming model also arrives at length
20for the given example.Output:
Output for 9x6 example:
Output for 6x9 example (intermediate solution after 90s):