0

I have tried to solve this problem for about 2 hours. I am not capable of solving. Does anyone have an idea on how to go about solving it? I tried using Python v. 3+

Any help would be greatly appreciated:

Given a two-dimensional array of letters, find the longest path that you can create by moving between adjacent letters in the alphabet - for example, if you are on a D, you may move to an E or a C. You may move up, down, left, or right by a single row or column, but not diagonally or more than one space. You may start at any square, and you may only use a given row/column pair once.

Return an ordered list of row/column pairs that represents the longest path. If there is a tie between two paths, return the one that starts with the lowest row index, and if that is also a tie, use the one with the lowest row and column indices. (If there is still a tie, returning either path is acceptable.)

Example input

A B H F
C C D G
A B D F

Example output

ABCBA

Clarifications The array will always contain at least one value. A and Z are not considered ‘adjacent’ letters. All lines will contain the same number of letters.

kaya3
  • 47,440
  • 4
  • 68
  • 97
  • 1
    Please post your best attack. This is a straightforward graph traversal -- once you identify this as a graph. Where are you stuck? – Prune Nov 23 '19 at 01:15
  • 1
    It is not a straightforward graph traversal; it is an NP-hard problem. Some sort of graph traversal algorithm can find you the greatest distance between two nodes, but that is not the same as the problem of finding the longest path. – kaya3 Nov 23 '19 at 02:24

1 Answers1

1

This problem can be modelled as an instance of the longest path problem in a graph.

Construct a graph where each character is a node in the graph, and nodes for adjacent characters have an edge if and only if their letters are 1 apart in the alphabet. The problem asks for the longest non-self-intersecting path in this graph.

In the general case, the longest path problem is NP-hard. But this is a restricted case of the problem because the graph is a subgraph of a grid. Nonetheless, it is still NP-hard. The reason for this is that any longest-path algorithm can be used to solve the Hamiltonian path problem, which asks if there is a path visiting every vertex in the graph. For the class of partial grid graphs, the Hamiltonian path problem is NP-complete. So the best you are going to do will be some kind of backtracking search.

kaya3
  • 47,440
  • 4
  • 68
  • 97