A truck fleet dispatcher is trying to determine which routes are still accessible after heavy rains flood certain highways. During their trips, trucks must follow linear, ordered paths between 26
waypoints labeled A
through Z
; in other words, they must traverse waypoints in either standard or reverse alphabetical order.
The only data the dispatcher can use is the trip logbook, which contains a record of the recent successful trips. The logbook is represented as a list of strings, where each string (corresponding to one entry) has two characters corresponding to the trip origin and destination waypoints respectively.
If the logbook contains a record of a successful trip between two points, it can be assumed that the full path between those points is accessible. Note that logbook entries imply that both directions of the traversal are valid. For example, an entry of RP
means that trucks can move along both R --> Q --> P
and P --> Q --> R
. Note that the trips A --> B
and C -> D
do not together imply that B -> C
is usable. Entries can have the same character twice, such as C -> C
, but this indicates no paths.
Given an array of logbook entries, your task is to write a function to return the length of the longest consecutive traversal possible; in other words, compute the maximum number of consecutive edges known to be safe. (In even more formal terms, compute the diameter of the largest tree on this graph.)
Example
For logbook = ["BG", "CA", "FI", "OK"]
, the output should be 8
Because we can get both from A
to C
and from B
to G
, we can thus get from A
to G
. Because we can get from F
to I
and access I
from G
, we can therefore traverse A --> I
. This corresponds to a traversal length of 8
since 8
edges connect these 9
waypoints. O
through K
is a length 4
traversal. These two paths are disjoint, so no longer consecutive paths can be found and the answer is 8
.
Guaranteed constraints:
1 ≤ logbook.length ≤ 100
,
logbook[i].length = 2
,
logbook[i][j] ∈ ['A'..'Z']
.
Test Cases:
logbook: ["AZ"]
Output:25
logbook: ["AB", "CD"]
Output:1
logbook: ["BG", "CA", "FI", "OK"]
Output: 8
logbook: ["KM", "SQ", "ON", "XM", "UK"]
Output:13
logbook: ["XU", "WY", "ZD", "HH", "BK", "LG"]
Output: 24
logbook: ["QR", "PC", "TK", "OE", "YQ", "IJ", "HB"]
Output: 23
logbook: ["MG", "QQ", "JV", "IZ", "SQ", "PN", "TI", "NK"]
Output: 19
logbook: ["II", "ZW", "CI", "DT", "IM", "II", "TR", "XO", "AL"]
Output: 25
The input will always be an array of strings, each of which has exactly two characters corresponding to the trip origin and destination waypoints respectively. The characters will always be letters, in a consistent case of your choice. The input will never contain more than 100 pairs.
Your program should output the longest consecutive traversal possible (number of edges) given the input.
This is code-golf so the shortest code in bytes wins