Skip to content

Commit 8573ae9

Browse files
authored
Create 1617-count-subtrees-with-max-distance-between-cities.js
1 parent 57db01b commit 8573ae9

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @return {number[]}
5+
*/
6+
const countSubgraphsForEachDiameter = function (n, edges) {
7+
const graph = {};
8+
for (let [u, v] of edges) {
9+
if (!graph[u - 1]) graph[u - 1] = [];
10+
if (!graph[v - 1]) graph[v - 1] = [];
11+
graph[u - 1].push(v - 1);
12+
graph[v - 1].push(u - 1);
13+
}
14+
let ans = Array(n - 1).fill(0);
15+
for (let i = 1, len = 2 ** n; i < len; i++) {
16+
const d = maxDistance(i);
17+
if (d > 0) ans[d - 1] += 1;
18+
}
19+
return ans;
20+
function bfs(src, cities) {
21+
const visited = new Set();
22+
visited.add(src);
23+
const q = [[src, 0]]; // Pair of (vertex, distance)
24+
let farthestDist = 0; // Farthest distance from src to other nodes
25+
while (q.length > 0) {
26+
const [u, d] = q.shift();
27+
farthestDist = d;
28+
for (let v of graph[u]) {
29+
if (!visited.has(v) && cities.has(v)) {
30+
visited.add(v);
31+
q.push([v, d + 1]);
32+
}
33+
}
34+
}
35+
return [farthestDist, visited];
36+
}
37+
function maxDistance(state) {
38+
// return: maximum distance between any two cities in our subset. O(n^2)
39+
const cities = new Set();
40+
for (let i = 0; i < n; i++) {
41+
if ((state >> i) & (1 === 1)) cities.add(i);
42+
}
43+
let ans = 0;
44+
for (let i of cities) {
45+
const [farthestDist, visited] = bfs(i, cities);
46+
if (visited.size < cities.size) return 0; // Can't visit all nodes of the tree -> Invalid tree
47+
ans = Math.max(ans, farthestDist);
48+
}
49+
return ans;
50+
}
51+
};

0 commit comments

Comments
 (0)