Skip to content

Commit 0f5cf0c

Browse files
Create 1466-Reorder-Routes-to-Make- All-Paths-Lead-to-the-City-Zero.cs
1 parent 28028a9 commit 0f5cf0c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
public class Solution {
2+
public int MinReorder(int n, int[][] connections)
3+
{
4+
if (connections == null || connections?.Length < 2) return 0;
5+
6+
Dictionary<int, HashSet<int>> paths = new Dictionary<int, HashSet<int>>();
7+
List<int>[] graph = new List<int>[n];
8+
foreach (var connection in connections)
9+
{
10+
if (!paths.ContainsKey(connection[0]))
11+
paths.Add(connection[0], new HashSet<int>());
12+
13+
paths[connection[0]].Add(connection[1]);
14+
15+
if (graph[connection[0]] == null)
16+
graph[connection[0]] = new List<int>();
17+
graph[connection[0]].Add(connection[1]);
18+
19+
if (graph[connection[1]] == null)
20+
graph[connection[1]] = new List<int>();
21+
graph[connection[1]].Add(connection[0]);
22+
}
23+
int cnt = 0;
24+
HashSet<int> visited = new HashSet<int>();
25+
DFSMinReorder(graph, 0, paths, visited, ref cnt);
26+
return cnt;
27+
}
28+
29+
private void DFSMinReorder(List<int>[] graph, int u, Dictionary<int, HashSet<int>> paths, HashSet<int> visited, ref int cnt)
30+
{
31+
visited.Add(u);
32+
33+
if (graph[u] != null)
34+
{
35+
foreach (var v in graph[u])
36+
{
37+
if (!visited.Contains(v))
38+
{
39+
if (paths.ContainsKey(u) && paths[u].Contains(v))
40+
cnt++;
41+
42+
DFSMinReorder(graph, v, paths, visited, ref cnt);
43+
}
44+
}
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)