-
Notifications
You must be signed in to change notification settings - Fork 5
/
ReorderRoutesToMakeAllPathsLeadToTheCityZero.java
64 lines (59 loc) · 2.21 KB
/
ReorderRoutesToMakeAllPathsLeadToTheCityZero.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/*/
class Solution {
public int minReorder(int n, int[][] connections) {
Map<Integer,Set<Integer>> diGraph = new HashMap<Integer,Set<Integer>>();
Map<Integer,List<Integer>> graph = new HashMap<Integer,List<Integer>>();
int V = 0;
for (int[] edge : connections)
{
graph.putIfAbsent(edge[0], new ArrayList<Integer>());
graph.putIfAbsent(edge[1], new ArrayList<Integer>());
diGraph.putIfAbsent(edge[0], new HashSet<Integer>());
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
diGraph.get(edge[0]).add(edge[1]);
V = Math.max(V,edge[0]);
V = Math.max(V,edge[1]);
}
boolean[] visited = new boolean[V+1];
Queue<Integer> queue = new LinkedList<Integer>();
int count = 0;
queue.add(0);
while (!queue.isEmpty())
{
int vertex = queue.poll();
visited[vertex] = true;
for (int adjVertex : graph.get(vertex))
{
if (!visited[adjVertex] && diGraph.containsKey(vertex) && diGraph.get(vertex).contains(adjVertex))
++count;
if (!visited[adjVertex]) queue.add(adjVertex);
}
}
return count;
}
}
class Solution {
public int minReorder(int n, int[][] connections) {
Map<Integer,List<Integer>> graph = new HashMap<Integer,List<Integer>>();
for (int[] edge : connections)
{
graph.putIfAbsent(edge[0],new ArrayList<Integer>());
graph.putIfAbsent(edge[1],new ArrayList<Integer>());
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(-edge[0]);
}
return dfs(graph,0,new boolean[n]);
}
public int dfs(Map<Integer,List<Integer>> graph, int src, boolean[] visited)
{
visited[src] = true;
int result = 0;
for (Integer adjNode : graph.get(src))
{
if (!visited[Math.abs(adjNode)])
result += dfs(graph,Math.abs(adjNode),visited)+(adjNode > 0 ? 1 : 0);
}
return result;
}
}