48. Counting computer networks
Easy
There are n computers numbered from 0 to n - 1 and a list of cables connecting pairs of computers. One computer can reach another if there is a path of cables between them; reachability is also transitive.
Return the number of separate networks. A network is a maximal group of computers where every pair can reach each other. Computers with no cables also form individual networks.
Example 1
Input: n = 5, cabos = [[0, 1], [1, 2], [3, 4]]
Output: 2
Explanation: Computers 0, 1, and 2 form one network, while computers 3 and 4 form another.
Example 2
Input: n = 4, cabos = []
Output: 4
Explanation: With no cables, each computer forms its own network.
Example 3
Input: n = 6, cabos = [[0, 1], [1, 2], [2, 0], [3, 4], [4, 3]]
Output: 3
Explanation: There are two networks connected by cables and one isolated computer.
Constraints
- 0 <= n <= 10^5
- 0 <= cabos.length <= 2 * 10^5
- Each cable has exactly two endpoints.
- 0 <= cabos[i][0], cabos[i][1] < n
GraphsUnion-find
Saved in this browser
Caso 1
n =
5
cabos =
[[0,1],[1,2],[3,4]]
Expected =
2
Caso 2
n =
4
cabos =
[]
Expected =
4
Caso 3
n =
6
cabos =
[[0,1],[1,2],[2,0],[3,4],[4,3]]
Expected =
3
Run checks these 3 cases. Submit runs all 11, including hidden ones.