Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Each beacon is represented as (x, y, r)
- * ToDo: Your changes go here
- */
- function maximumActivations(beacons) {
- const graph = new Map();
- const visited = new Set();
- // Create a graph where each node is a beacon and edges are drawn between
- // two nodes if the range of one node covers the other node
- for (let i = 0; i < beacons.length; i++) {
- for (let j = i + 1; j < beacons.length; j++) {
- const [x1, y1, r1] = beacons[i];
- const [x2, y2, r2] = beacons[j];
- const distance = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
- if (distance <= r1 + r2) {
- if (!graph.has(i)) graph.set(i, []);
- if (!graph.has(j)) graph.set(j, []);
- graph.get(i).push(j);
- graph.get(j).push(i);
- }
- }
- }
- let maxSize = 0;
- // Perform DFS from each node and keep track of the size of the connected component
- for (let i = 0; i < beacons.length; i++) {
- if (!visited.has(i)) {
- let size = {val: 0};
- dfs(i, size);
- maxSize = Math.max(maxSize, size.val);
- }
- }
- function dfs(node, size) {
- visited.add(node);
- size.val++;
- if (graph.has(node)) {
- for (const nextNode of graph.get(node)) {
- if (!visited.has(nextNode)) {
- dfs(nextNode, size);
- }
- }
- }
- }
- return maxSize;
- }
- function testSolution() {
- testCases = [
- [[1, 2, 3], [2, 3, 1], [3, 4, 2], [4, 5, 3], [5, 6, 4]],
- [[1, 2, 3], [2, 3, 1], [3, 4, 2], [4, 5, 2], [7, 7, 1]],
- [[1, 1, 5], [10, 10, 5]],
- [[2, 1, 3], [6, 1, 4]],
- [[1, 2, 3], [3, 4, 2], [8, 9, 2], [6, 7, 1], [5, 5, 1]],
- [[1, 2, 3], [3, 4, 2], [8, 9, 2], [6, 7, 1], [5, 5, 1], [0, 0, 1]],
- ]
- maxActivations = [5, 4, 1, 2, 2, 3]
- let success = 0
- for (let id = 0; id < testCases.length; id++) {
- if (maximumActivations(testCases[id]) == maxActivations[id]) success += 1
- }
- console.log(`# of test cases passed: ${success}/${testCases.length}`)
- }
- testSolution()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement