A vault system is described by a string of directed corridors. Each corridor leads from one room to another and has a traversal cost. Room 0 is the entrance and the vault is the highest-numbered room.
Parse the string and return every path from the entrance to the vault in non-decreasing order of total cost. A path is the list of room numbers visited, starting at 0 and ending at the vault, and it may not visit any room twice. When two paths have the same total cost, order them lexicographically by their room sequence.
Function Signature
def vault_paths(corridors: str) -> list[list[int]]:
Rules
-
Each corridor is written as
(src,dst,cost)
and corridors are separated by
;
, for example
"(0,1,5);(0,2,3)"
. A corridor can only be walked from
src
to
dst
.
-
The vault is the largest room number that appears anywhere in the string, as a source or a destination.
-
The cost of a path is the sum of the costs of its corridors.
-
Paths are ordered by total cost ascending. Ties are broken by comparing the room sequences position by position: at the first position where they differ, the path with the smaller room number comes first.
-
If two corridors join the same ordered pair of rooms, each one gives its own path, so the same room sequence can appear more than once with different costs.
Constraints
-
2 <= number of rooms <= 8
-
0 <= cost <= 100
-
The input string is well-formed and follows the format
"(src,dst,cost);(src,dst,cost);..."
.
-
Corridors are directed.
-
There is at least one path from room
0
to the vault.
Examples
Input: corridors = "(0,1,5);(0,2,3);(1,3,2);(2,3,7);(2,1,1)"
Output: [[0,2,1,3],[0,1,3],[0,2,3]]
Room 3 is the vault. The three paths cost 3 + 1 + 2 = 6, 5 + 2 = 7 and 3 + 7 = 10, so the path through the most rooms comes first because it is the cheapest.
Input: corridors = "(0,1,1);(0,2,1);(1,3,1);(2,3,1)"
Output: [[0,1,3],[0,2,3]]
Both paths cost 2, so the tie is broken lexicographically: [0,1,3] comes before [0,2,3] because its second room is smaller.
Input: corridors = "(0,1,0);(1,0,0);(1,2,4);(0,2,4)"
Output: [[0,1,2],[0,2]]
Room 2 is the vault and both paths cost 4. [0,1,2] comes first because its second room, 1, is smaller than 2; the number of rooms in a path plays no part in the tie-break. The corridor from room 1 back to room 0 is never used, since it would revisit the entrance.