|
| 1 | +/** |
| 2 | + * 1319. Number of Operations to Make Network Connected |
| 3 | + * https://leetcode.com/problems/number-of-operations-to-make-network-connected/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming |
| 7 | + * a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. |
| 8 | + * Any computer can reach any other computer directly or indirectly through the network. |
| 9 | + * |
| 10 | + * You are given an initial computer network connections. You can extract certain cables between |
| 11 | + * two directly connected computers, and place them between any pair of disconnected computers to |
| 12 | + * make them directly connected. |
| 13 | + * |
| 14 | + * Return the minimum number of times you need to do this in order to make all the computers |
| 15 | + * connected. If it is not possible, return -1. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} n |
| 20 | + * @param {number[][]} connections |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var makeConnected = function(n, connections) { |
| 24 | + const parent = Array(n).fill(-1); |
| 25 | + let isNotConnected = n - 1; |
| 26 | + let count = 0; |
| 27 | + |
| 28 | + connections.forEach(([node, connection]) => { |
| 29 | + if (search(node) !== search(connection)) { |
| 30 | + const p1 = search(node); |
| 31 | + const p2 = search(connection); |
| 32 | + if (p1 !== p2) { |
| 33 | + parent[p2] = p1; |
| 34 | + } |
| 35 | + isNotConnected--; |
| 36 | + } else { |
| 37 | + count++; |
| 38 | + } |
| 39 | + }); |
| 40 | + |
| 41 | + return isNotConnected <= count ? isNotConnected : -1; |
| 42 | + |
| 43 | + function search(node) { |
| 44 | + if (parent[node] === -1) { |
| 45 | + return node; |
| 46 | + } |
| 47 | + parent[node] = search(parent[node]); |
| 48 | + return parent[node]; |
| 49 | + } |
| 50 | +}; |
0 commit comments