GIJOE
GIJOE

Reputation: 41

Find longest route in 2D array

So I got this assignment which I am not sure how to aprroach. I got a 2D array in which some cells are forbidden to visit. Then I need to traverse the whole array choosing the longest route without entering the forbidden cells. I can also not "go back" and take another turn, the traversal should always go "forward". The output should be the number of cells visited and in the correct order. The algorithm should be farily scalable, at least for an array with 100x100 cells. Below is a picture showing the task.

enter image description here

As in the picture above, there is really just two solutions: Either follow along the edge and then go down one cell and then up again, just like the example. Or it could just have followed along the complete edge. The number to cells visited should still be the same; 12.

Now I have searched alot on this and found many variations and to my understanding, I should be able to use maybe Djikstras, Bellman-Ford, A* algorithms or some kind of Depth/Breadth-first graph traversal. But I am totaly stuck and not sure where to go from here.

Upvotes: 4

Views: 888

Answers (1)

kgeorgiy
kgeorgiy

Reputation: 1477

This problem is NP-hard, as shown in A. Itai, C. Papadimitriou, J. Szwarcfiter, Hamiltonian paths in grid graphs. So no exact polynomial time algorithm exist.

In practice, the problem of you size should be solvable by modern Constraint Solvers. The review of the methods how to make Constraint Problem for the longest path search could be found at Q. Pham, Y. Deville, Solving the Longest Simple Path Problem with Constraint-Based Techniques.

Upvotes: 1

Related Questions