using
System;
using
System.Collections.Generic;
using
System.Linq;
public
class
Solution {
private
void
dfs(
int
node, HashSet<
int
> vis,
Dictionary<
int
, List<
int
> > graph)
{
vis.Add(node);
foreach
(
int
adj
in
graph.GetValueOrDefault(
node,
new
List<
int
>()))
{
if
(!vis.Contains(adj)) {
dfs(adj, vis, graph);
}
}
}
public
List<
int
> Solve(
int
[][] edges)
{
Dictionary<
int
, List<
int
> > graph
=
new
Dictionary<
int
, List<
int
> >();
Dictionary<
int
,
int
> indeg
=
new
Dictionary<
int
,
int
>();
List<
int
> topoSort =
new
List<
int
>();
HashSet<
int
> vis =
new
HashSet<
int
>();
foreach
(
int
[] edge
in
edges)
{
int
u = edge[0];
int
v = edge[1];
if
(!graph.ContainsKey(u)) {
graph.Add(u,
new
List<
int
>());
}
graph[u].Add(v);
indeg[v] = indeg.GetValueOrDefault(v, 0) + 1;
}
Queue<
int
> qu =
new
Queue<
int
>();
foreach
(
int
u
in
graph.Keys)
{
if
(!indeg.ContainsKey(u)) {
qu.Enqueue(u);
}
}
while
(qu.Count() != 0) {
int
node = qu.Dequeue();
topoSort.Add(node);
foreach
(
int
adj
in
graph.GetValueOrDefault(
node,
new
List<
int
>()))
{
indeg[adj] = indeg[adj] - 1;
if
(indeg[adj] == 0) {
qu.Enqueue(adj);
}
}
}
vis =
new
HashSet<
int
>();
List<
int
> ans =
new
List<
int
>();
foreach
(
int
node
in
topoSort)
{
if
(!vis.Contains(node)) {
vis.Add(node);
ans.Add(node);
dfs(node, vis, graph);
}
}
return
ans;
}
public
static
void
Main()
{
Solution obj =
new
Solution();
int
[][] edges
= {
new
int
[] { 0, 1 },
new
int
[] { 2, 1 },
new
int
[] { 3, 2 },
new
int
[] { 4, 3 } };
List<
int
> ans = obj.Solve(edges);
Console.WriteLine(
string
.Join(
", "
, ans));
}
}