diff --git "a/problems/0332.\351\207\215\346\226\260\345\256\211\346\216\222\350\241\214\347\250\213.md" "b/problems/0332.\351\207\215\346\226\260\345\256\211\346\216\222\350\241\214\347\250\213.md" index 1d9c524b13f252c4c80d96ba7a624e94e6eca0ad..43de3fffbd16f220575c9698153894fd075bfd99 100644 --- "a/problems/0332.\351\207\215\346\226\260\345\256\211\346\216\222\350\241\214\347\250\213.md" +++ "b/problems/0332.\351\207\215\346\226\260\345\256\211\346\216\222\350\241\214\347\250\213.md" @@ -939,6 +939,111 @@ impl Solution { } } ``` +### C# + +```C# +public class Solution { + public IList FindItinerary(IList> tickets) + { + var targets = new Dictionary>(); + // 清空存储机票信息的字典 + var result = new List(); + + // 遍历所有机票,记录出发机场到到达机场的航班次数 + foreach (var ticket in tickets) + { + string from = ticket[0]; + string to = ticket[1]; + + if (!targets.ContainsKey(from)) + { + targets[from] = new SortedDictionary(); + } + + if (!targets[from].ContainsKey(to)) + { + targets[from][to] = 0; + } + + targets[from][to]++; + } + + // 行程从 JFK 机场开始 + result.Add("JFK"); + // 调用回溯函数开始查找行程 + Backtracking(tickets.Count, result,targets); + + return result; + } + + private bool Backtracking(int ticketNum, List result, Dictionary> targets) + { + // 当结果列表的长度等于机票数量加 1 时,说明找到了一条完整的行程 + if (result.Count == ticketNum + 1) + { + return true; + } + else if (result.Count > ticketNum + 1) + { + return false; + } + + // 获取当前所在机场 + string currentAirport = result[result.Count - 1]; + if (targets.ContainsKey(currentAirport)) + { + // 遍历当前机场的所有可到达机场 + var keys = targets[currentAirport].Keys.ToList(); + for (int i = 0; i < keys.Count; i++) + { + var key = keys[i]; + var target = targets[currentAirport][key]; + if (target > 0) + { + // 若该航班还有剩余次数,将该到达机场添加到结果列表 + result.Add(key); + // 减少该航班的剩余次数 + targets[currentAirport][key]--; + + // 递归调用回溯函数 + if (Backtracking(ticketNum, result, targets)) + { + return true; + } + + // 回溯操作,移除该到达机场并恢复航班剩余次数 + result.RemoveAt(result.Count - 1); + targets[currentAirport][key]++; + } + } + // foreach will through UE as targets[currentAirport] will be modifeid in different thread + //foreach (var target in targets[currentAirport]) + //{ + // if (target.Value > 0) + // { + // // 若该航班还有剩余次数,将该到达机场添加到结果列表 + // result.Add(target.Key); + // // 减少该航班的剩余次数 + // targets[currentAirport][target.Key]--; + + // // 递归调用回溯函数 + // if (Backtracking(ticketNum, result, targets)) + // { + // return true; + // } + + // // 回溯操作,移除该到达机场并恢复航班剩余次数 + // result.RemoveAt(result.Count - 1); + // targets[currentAirport][target.Key]++; + // } + //} + } + + return false; + } +} + +```