Skip to content

Commit d1591f8

Browse files
authored
Update Reorder Routes to Make All Paths Lead to the City Zero.java
1 parent f2c2a47 commit d1591f8

File tree

1 file changed

+26
-25
lines changed

1 file changed

+26
-25
lines changed
Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,31 @@
11
class Solution {
2-
public int minReorder(int n, int[][] connections) {
3-
Map<Integer, Set<Integer>> map = new HashMap<>();
4-
Set<String> set = new HashSet<>();
5-
for (int[] connection : connections) {
6-
map.computeIfAbsent(connection[0], k -> new HashSet<>()).add(connection[1]);
7-
map.computeIfAbsent(connection[1], k -> new HashSet<>()).add(connection[0]);
8-
set.add(connection[0] + "->" + connection[1]);
9-
}
10-
Queue<Integer> queue = new LinkedList<>();
11-
queue.add(0);
12-
int numOfReorders = 0;
13-
boolean[] visited = new boolean[n];
14-
visited[0] = true;
15-
while (!queue.isEmpty()) {
16-
int removed = queue.remove();
17-
for (int connection : map.getOrDefault(removed, new HashSet<>())) {
18-
if (visited[connection]) {
19-
continue;
2+
public int minReorder(int n, int[][] connections) {
3+
Map<Integer, List<List<Integer>>> graph = new HashMap<>();
4+
for (int[] conn : connections) {
5+
graph.computeIfAbsent(conn[0], k -> new ArrayList<>()).add(List.of(conn[1], 1));
6+
graph.computeIfAbsent(conn[1], k -> new ArrayList<>()).add(List.of(conn[0], 0));
207
}
21-
visited[connection] = true;
22-
if (!set.contains(connection + "->" + removed)) {
23-
numOfReorders++;
8+
int[] count = {0};
9+
bfs(0, n, graph, count);
10+
return count[0];
11+
}
12+
13+
private void bfs(int node, int n, Map<Integer, List<List<Integer>>> graph, int[] count) {
14+
Queue<Integer> queue = new LinkedList<>();
15+
boolean[] visited = new boolean[n];
16+
visited[node] = true;
17+
queue.add(node);
18+
while (!queue.isEmpty()) {
19+
int removed = queue.remove();
20+
for (List<Integer> conn : graph.getOrDefault(removed, new ArrayList<>())) {
21+
int neighbor = conn.get(0);
22+
int direction = conn.get(1);
23+
if (!visited[neighbor]) {
24+
count[0] += direction;
25+
visited[neighbor] = true;
26+
queue.add(neighbor);
27+
}
28+
}
2429
}
25-
queue.add(connection);
26-
}
2730
}
28-
return numOfReorders;
29-
}
3031
}

0 commit comments

Comments
 (0)