Skip to content

Commit 228fdac

Browse files
committed
Add solution #1319
1 parent 9797127 commit 228fdac

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,7 @@
382382
1313|[Decompress Run-Length Encoded List](./1313-decompress-run-length-encoded-list.js)|Easy|
383383
1317|[Convert Integer to the Sum of Two No-Zero Integers](./1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy|
384384
1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium|
385+
1319|[Number of Operations to Make Network Connected](./1319-number-of-operations-to-make-network-connected.js)|Medium|
385386
1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy|
386387
1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium|
387388
1331|[Rank Transform of an Array](./1331-rank-transform-of-an-array.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)