LeetCode: 332. Reconstruct Itinerary
题目描述
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to]
, reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK
. Thus, the itinerary must begin with JFK
.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"]
has a smaller lexical order than ["JFK", "LGB"]
.
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
But it is larger in lexical order.
解题思路 —— 排序 + DFS
先按照字典序排序,然后按照排号序的航线进行 DFS,第一个搜出来的路径就是所求路径
AC 代码
/*
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
*/
type TicketSlice [][]string
func (this TicketSlice) Len() int {
return len(this)
}
func (this TicketSlice) Less(i, j int) bool {
if this[i][0] < this[j][0] {
return true
} else if this[i][0] == this[j][0] && this[i][1] <= this[j][1] {
return true
} else {
return false
}
}
func (this TicketSlice) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}
func dfs(tickets [][]string, record []string, cur string) []string {
record = append(record, cur)
if len(tickets) == 0 {
return record
}
for i := 0; i < len(tickets); i++ {
if tickets[i][0] == cur {
var newTickets [][]string
newTickets = append(newTickets, tickets[:i]...)
newTickets = append(newTickets, tickets[i+1:]...)
ans := dfs(newTickets, record, tickets[i][1])
if len(ans) != 0 {
return ans
}
}
}
return []string{}
}
func findItinerary(tickets [][]string) []string {
if len(tickets) == 0 {
return []string{}
}
sort.Sort(TicketSlice(tickets))
ans := dfs(tickets, []string{}, "JFK")
return ans
}