There are
n
computers numbered from0
ton - 1
connected by ethernet cables connections forming a network whereconnections[i] = [a_i, b_i]
represents a connection between computersa_i
andb_i
. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial computer networkconnections
. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return-1
.
Constraints:
1 <= n <= 105
1 <= connections.length <= min(n * (n - 1) / 2, 105)
connections[i].length == 2
0 <= ai, bi < n
ai != bi
- There are no repeated connections.
- No two computers are connected by more than one cable.
有
n
台電腦分別被編號為0
到n - 1
,且他們被電纜線連接成一個網路,一段連接connections[i] = [a_i, b_i]
代表電腦a_i
和b_i
之間的連接。所有電腦可以透過網路直接或間接地探索到任何其他電腦。
給你一個初始的電腦網路connections
。你可以拔除兩台有連接的電腦之間的電纜,並且將電纜放回任何一對未連接的電腦將其連接。
回傳當所有的電腦都連接時,你拔除並重接電纜的最小次數。如果這不可能做到,回傳-1
。
限制:
1 <= n <= 105
1 <= connections.length <= min(n * (n - 1) / 2, 105)
connections[i].length == 2
0 <= ai, bi < n
ai != bi
- 不會有重複的連接。
- 不會有兩台電腦被超過一條的電纜連接。
n
,當電纜數量大於 n - 1
時必定可以全連接;反之則無法連接,直接回傳 -1
g
,答案為 g - 1
vector<vector<int>>
儲存,但發現會吃 TLE 過不了,因此需要改為 vector<int>*
進行加速LeetCode
C++