Skip to content

Commit 70f3db6

Browse files
committed
[PGS] 체육복 / Level 1 / 50분(힌트 사용->성공)
1 parent e096c63 commit 70f3db6

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def dfs(start, graph, visited, check_link):
2+
cnt = 1
3+
visited[start] = True # 방문 체크
4+
for v in graph[start]: # v에 연결되어 있는 다른 노드 탐색.
5+
if visited[v] == False and check_link[start][v] == True:
6+
# 연결되어 있지만 방문한 적 없다면 -> DFS 호출하고, 반환값을 cnt에 누적해서 더함
7+
cnt += dfs(v, graph, visited, check_link)
8+
return cnt
9+
10+
def solution(n, wires):
11+
answer = float("inf") # answer 초기화
12+
check_link = [[True]*(n+1) for _ in range(n+1)] # 끊은 간선인지 아닌지 체크하는 용도
13+
graph = [[] for _ in range(n+1)] # 송전탑 그래프
14+
15+
# 그래프 연결
16+
for u, v in wires:
17+
graph[u].append(v)
18+
graph[v].append(u)
19+
20+
# 전력망 나누기
21+
for a, b in wires:
22+
# 1. 간선 정보를 확인하면서 a, b 그룹에 연결된 송전탑 개수를 세기 위해서 a에서 b로 가는 간선을 끊어본다.
23+
visited = [False] * (n+1)
24+
check_link[a][b] = False # 양망향 연결 끊기
25+
# 2. a와 b에 붙어있는 송전탑 개수
26+
cnt_a = dfs(a, graph, visited, check_link) # a랑 붙어있는 송전탑 개수
27+
cnt_b = dfs(b, graph, visited, check_link) # b랑 붙어있는 송전탑 개수
28+
check_link[a][b] = True
29+
30+
answer = min(answer, abs(cnt_a - cnt_b)) # 송전탑 개수의 차이(절대값) 가장 작은 걸로 저장함
31+
32+
return answer

0 commit comments

Comments
 (0)