Skip to content

Commit 46a6a07

Browse files
authored
Update 1617-count-subtrees-with-max-distance-between-cities.js
1 parent d1eb318 commit 46a6a07

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

1617-count-subtrees-with-max-distance-between-cities.js

+67
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,70 @@ const countSubgraphsForEachDiameter = function (n, edges) {
4949
return ans;
5050
}
5151
};
52+
53+
// another
54+
55+
/**
56+
* @param {number} n
57+
* @param {number[][]} edges
58+
* @return {number[]}
59+
*/
60+
const countSubgraphsForEachDiameter = function(n, edges) {
61+
const graph = {}
62+
for(const [u, v] of edges) {
63+
if(graph[u - 1] == null) graph[u - 1] = []
64+
if(graph[v - 1] == null) graph[v - 1] = []
65+
graph[u - 1].push(v - 1)
66+
graph[v - 1].push(u - 1)
67+
}
68+
const res = Array(n - 1).fill(0)
69+
70+
for(let i = 0, len = 2 ** n; i < len; i++) {
71+
const dis = maxDistance(i)
72+
if(dis > 0) res[dis - 1]++
73+
}
74+
75+
return res
76+
77+
function bfs(src, cities) {
78+
const visited = new Set([src])
79+
let q = [[src, 0]]
80+
let maxDist = 0
81+
while(q.length) {
82+
const tmp = []
83+
const size = q.length
84+
for(let i = 0; i < size; i++) {
85+
const [u, d] = q[i]
86+
maxDist = d
87+
for(const v of (graph[u] || [])) {
88+
if(cities.has(v) && !visited.has(v)) {
89+
visited.add(v)
90+
tmp.push([v, d + 1])
91+
}
92+
}
93+
}
94+
95+
q = tmp
96+
}
97+
98+
return [maxDist, visited]
99+
}
100+
101+
function maxDistance(state) {
102+
const cities = new Set()
103+
for(let i = 0; i < n; i++) {
104+
if(state & (1 << i)) cities.add(i)
105+
}
106+
107+
let res = 0
108+
for(const e of cities) {
109+
const [maxDist, visited] = bfs(e, cities)
110+
if(visited.size < cities.size) return 0
111+
res = Math.max(res, maxDist)
112+
}
113+
114+
return res
115+
}
116+
};
117+
118+

0 commit comments

Comments
 (0)