Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1016 from agnihotriketan/patch-7
Browse files Browse the repository at this point in the history
C# 332-Reconstruct-Itinerary.cs
  • Loading branch information
Ahmad-A0 authored Sep 4, 2022
2 parents 619ebf1 + ff00673 commit 8cecf73
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions csharp/332-Reconstruct-Itinerary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
public class Solution {
public IList<string> FindItinerary(IList<IList<string>> tickets)
{
var map = new Dictionary<string, List<string>>();
foreach (var ticket in tickets)
{
if (!map.TryGetValue(ticket[0], out var adj))
{
adj = new List<string>();
map.Add(ticket[0], adj);
}
adj.Add(ticket[1]);
}

foreach (var adj in map.Values)
{
adj.Sort(Comparer<string>.Create((a, b) => string.Compare(b, a)));
}

var res = new Stack<string>();
DfsVisit(map, "JFK", res);
return res.ToList();
}

private void DfsVisit(Dictionary<string, List<string>> map, string src, Stack<string> ans)
{
if (map.TryGetValue(src, out var adj))
{
while (adj.Count > 0)
{
var next = adj.Last();
adj.RemoveAt(adj.Count - 1);
DfsVisit(map, next, ans);
}
}
ans.Push(src);
}
}

0 comments on commit 8cecf73

Please sign in to comment.