|
| 1 | +// https://leetcode.com/problems/reconstruct-itinerary/submissions/ |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "sort" |
| 7 | +) |
| 8 | + |
| 9 | +func findItinerary(tickets [][]string) []string { |
| 10 | + r := NewReconstruct("JFK", tickets) |
| 11 | + return r.Itinerary() |
| 12 | +} |
| 13 | + |
| 14 | +type Reconstruct struct { |
| 15 | + adjList map[string][]string |
| 16 | + edgeUsed map[string][]bool |
| 17 | + used, total int |
| 18 | + path []string |
| 19 | + startIATA string |
| 20 | +} |
| 21 | + |
| 22 | +func NewReconstruct(startIATA string, tickets [][]string) *Reconstruct { |
| 23 | + r := new(Reconstruct) |
| 24 | + r.total = len(tickets) |
| 25 | + r.startIATA = startIATA |
| 26 | + r.makeAdjList(tickets) |
| 27 | + return r |
| 28 | +} |
| 29 | + |
| 30 | +func (r *Reconstruct) makeAdjList(tickets [][]string) { |
| 31 | + r.adjList = make(map[string][]string) |
| 32 | + for _, ticket := range tickets { |
| 33 | + dep, arr := ticket[0], ticket[1] |
| 34 | + adj := r.adjList[dep] |
| 35 | + r.adjList[dep] = append(adj, arr) |
| 36 | + } |
| 37 | + for iata, tickets := range r.adjList { |
| 38 | + sort.Slice(tickets, func(i, j int) bool { return tickets[i] < tickets[j] }) |
| 39 | + r.adjList[iata] = tickets |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func (r *Reconstruct) Itinerary() []string { |
| 44 | + r.used = 0 |
| 45 | + r.path = make([]string, 0) |
| 46 | + r.path = append(r.path, r.startIATA) |
| 47 | + r.edgeUsed = make(map[string][]bool) |
| 48 | + r.dfs(r.startIATA) |
| 49 | + return r.path |
| 50 | +} |
| 51 | + |
| 52 | +func (r *Reconstruct) dfs(iata string) { |
| 53 | + for arrIdx, arrIATA := range r.adjList[iata] { |
| 54 | + |
| 55 | + if r.isEdgeUsed(iata, arrIdx) { |
| 56 | + continue |
| 57 | + } |
| 58 | + |
| 59 | + r.used++ |
| 60 | + r.path = append(r.path, arrIATA) |
| 61 | + r.setEdgeUsed(iata, arrIdx, true) |
| 62 | + |
| 63 | + r.dfs(arrIATA) |
| 64 | + if r.used == r.total { |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + r.setEdgeUsed(iata, arrIdx, false) |
| 69 | + r.path = r.path[:len(r.path)-1] |
| 70 | + r.used-- |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +func (r *Reconstruct) setEdgeUsed(iata string, arrIdx int, isUsed bool) { |
| 75 | + usedEdges, ok := r.edgeUsed[iata] |
| 76 | + if !ok { |
| 77 | + usedEdges = make([]bool, len(r.adjList[iata])) |
| 78 | + } |
| 79 | + usedEdges[arrIdx] = isUsed |
| 80 | + r.edgeUsed[iata] = usedEdges |
| 81 | +} |
| 82 | + |
| 83 | +func (r *Reconstruct) isEdgeUsed(iata string, arrIdx int) bool { |
| 84 | + usedEdges, ok := r.edgeUsed[iata] |
| 85 | + if !ok { |
| 86 | + usedEdges = make([]bool, len(r.adjList[iata])) |
| 87 | + } |
| 88 | + return usedEdges[arrIdx] |
| 89 | +} |
0 commit comments