There are n computers numbered from 0 to n - 1 connected by ethernet cables connections
forming a network where connections[i] = [ai, bi]
represents a connection between computers ai and bi. Any computer can reach any other computer
directly or indirectly through the network.
You are given an initial computer network connections.
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.
0~n-1까지의 번호가 붙은 n개의 컴퓨터가 [] 네트워크 쌍으로 연결되어 있다.
초기 네트워크의 상태가 주어졌을때, 당신은 특정 연결쌍을 끊고 다른 연결쌍을 생성할수 있습니다.
모든 컴퓨터가 상호간 연결되도록 하기 위해 몇번이나 연결쌍을 교체해야 할까요?
만약 불가능하다면 -1을 리턴하세요.
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: 1-2 연결된 케이블을 뽑고 1-3에 연결하면 된다.
from typing import List, Set
class Node:
def __init__(self):
self.to = set()
def addLine(self, i):
self.to.add(i)
class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
if n - 1 > len(connections): return -1
graph = [Node() for _ in range(n)]
for con in connections:
graph[con[0]].addLine(con[1])
graph[con[1]].addLine(con[0])
check = [0] * n
def dfs(x: int):
check[x] = 1
for next in graph[x].to:
if not check[next]:
dfs(next)
island = 0
for computer in range(n):
if not check[computer]:
dfs(computer)
island += 1
return island - 1