Notion에서 작성한 글이라, 여기에서 더 깔끔하게 보실 수 있습니다! 😮😊
def dfs(v, adj, visited):
visited.add(v)
for nxt in adj[v]:
if nxt not in visited:
dfs(nxt, adj, visited)
return 1
def solution(n, computers):
adj = [[] for _ in range(n)]
for i in range(n):
for j in range(n):
if i<j and computers[i][j]:
adj[i].append(j)
adj[j].append(i)
visited = set()
return sum(dfs(v, adj, visited) for v in range(n) if v not in visited)
def dfs(v, adj, visited):
stack = [v]
visited.add(v)
while stack:
for nxt in adj[stack.pop()]:
if nxt not in visited:
stack.append(nxt)
visited.add(nxt)
return 1
def solution(n, computers):
adj = [[] for _ in range(n)]
for i in range(n):
for j in range(n):
if i<j and computers[i][j]:
adj[i].append(j)
adj[j].append(i)
visited = set()
return sum(dfs(v, adj, visited) for v in range(n) if v not in visited)
def bfs(v, adj, visited):
queue = deque([v])
visited.add(v)
while queue:
for nxt in adj[queue.popleft()]:
if nxt not in visited:
queue.append(nxt)
visited.add(nxt)
return 1
def solution(n, computers):
adj = [[] for _ in range(n)]
for i in range(n):
for j in range(n):
if i<j and computers[i][j]:
adj[i].append(j)
adj[j].append(i)
visited = set()
return sum(bfs(v, adj, visited) for v in range(n) if v not in visited)
def find(p, x):
if p[x] < 0: return x
p[x] = find(p, p[x])
return p[x]
def union(p, x, y):
xs, ys = find(p, x), find(p, y)
if xs == ys: return
if p[xs] < p[ys]:
p[ys] = xs
else:
if p[xs] == p[ys]:
p[ys] -= 1
p[xs] = ys
def solution(n, computers):
p = [-1]*n
for i in range(n):
for j in range(n):
if i<j and computers[i][j]:
union(p, i, j)
return sum(p[v] < 0 for v in range(n))