Skip to content

Commit 9d0f142

Browse files
committed
Add solution #1466
1 parent 36cfc68 commit 9d0f142

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,7 @@
336336
1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium|
337337
1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy|
338338
1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy|
339+
1466|[Reorder Routes to Make All Paths Lead to the City Zero](./1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js)|Medium|
339340
1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy|
340341
1472|[Design Browser History](./1472-design-browser-history.js)|Medium|
341342
1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy|
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 1466. Reorder Routes to Make All Paths Lead to the City Zero
3+
* https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/
4+
* Difficulty: Medium
5+
*
6+
* There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way
7+
* to travel between two different cities (this network form a tree). Last year, The ministry
8+
* of transport decided to orient the roads in one direction because they are too narrow.
9+
*
10+
* Roads are represented by connections where connections[i] = [ai, bi] represents a road from
11+
* city ai to city bi.
12+
*
13+
* This year, there will be a big event in the capital (city 0), and many people want to travel
14+
* to this city.
15+
*
16+
* Your task consists of reorienting some roads such that each city can visit the city 0. Return
17+
* the minimum number of edges changed.
18+
19+
It's guaranteed that each city can reach city 0 after reorder.
20+
*/
21+
22+
/**
23+
* @param {number} n
24+
* @param {number[][]} connections
25+
* @return {number}
26+
*/
27+
var minReorder = function(n, connections) {
28+
const graph = new Array(n).fill(null).map(() => []);
29+
30+
connections.forEach(([k, v]) => {
31+
graph[k].push([v, 1]);
32+
graph[v].push([k, 0]);
33+
});
34+
35+
function dfs(node, parent) {
36+
let count = 0;
37+
38+
graph[node].forEach(([k, v]) => {
39+
if (k !== parent) {
40+
count += v;
41+
count += dfs(k, node);
42+
}
43+
});
44+
45+
return count;
46+
}
47+
48+
return dfs(0, -1);
49+
};

0 commit comments

Comments
 (0)