Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 94c8900

Browse files
solve the problem but with repetitions
1 parent 31d3e9a commit 94c8900

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

‎lab/exercises/10-mixed/critical-routers.js‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,60 @@
99
* @return {number[]} - The list of critical routers;
1010
*/
1111
function criticalRouters(numRouters, numLinks, links) {
12+
const graph = buildGraph(numRouters, links);
13+
const critical = [];
1214

15+
// console.log({graph});
16+
17+
for (let curr = 1; curr <= numRouters; curr++) {
18+
for (let i = 1; i <= numRouters; i++) {
19+
for (let j = 1; j <= numRouters; j++) {
20+
if (curr === i || curr === j || i === j) { continue; }
21+
if (!isConnected(graph, i, j, curr)) {
22+
critical.push(curr);
23+
i++;
24+
break;
25+
}
26+
}
27+
}
28+
}
29+
30+
return critical;
31+
}
32+
33+
function addEdge(graph, from, to) {
34+
// console.log('addEdge', {graph, from, to});
35+
const adjacents = graph.get(from);
36+
adjacents.add(to);
37+
}
38+
39+
function buildGraph(numRouters, links) {
40+
// console.log('buildGraph', { numRouters, links });
41+
const graph = new Map();
42+
const routers = [...Array(numRouters).keys()].map(r => r + 1);
43+
routers.forEach(r => graph.set(r, new Set()));
44+
45+
links.forEach(([from, to]) => {
46+
addEdge(graph, from, to);
47+
addEdge(graph, to, from);
48+
});
49+
50+
return graph;
51+
}
52+
53+
function isConnected(graph, i, j, ignore, visited = new Set()) {
54+
if (i === ignore || j === ignore) return false;
55+
if (graph.get(i).has(j)) return true;
56+
57+
for (const adj of graph.get(i)) {
58+
if (visited.has(adj)) { continue; }
59+
visited.add(adj);
60+
if (isConnected(graph, adj, j, ignore, visited)) {
61+
return true;
62+
}
63+
}
64+
65+
return false;
1366
}
1467

1568
module.exports = criticalRouters;

‎lab/exercises/10-mixed/critical-routers.spec.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ describe('Critical Routers', () => {
55
it('should work', () => {
66
const numRouters = 7;
77
const numLinks = 7;
8-
const links = [[0,1],[0,2], [1, 3], [2, 3], [2,5], [5, 6], [3,4]];
9-
expect(critialRouters(numRouters, numLinks, links)).toEqual([2,3,5]);
8+
const links = [[1,2], [1, 3], [2, 4], [3,4], [3, 6], [6,7],[4,5]];
9+
expect(critialRouters(numRouters, numLinks, links)).toEqual([3,4,6]);
1010
});
1111
});

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /