Skip to content

Commit

Permalink
[프로그래머스] 전력망을 둘로 나누기
Browse files Browse the repository at this point in the history
  • Loading branch information
ehdgua01 committed Sep 9, 2024
1 parent 446e29f commit a343bfd
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions coding_test/programmers/brute_force/split_electric_grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from collections import defaultdict, deque


def solution(n, wires):
answer = n
graph = defaultdict(set)
for v1, v2 in wires:
graph[v1].add(v2)
graph[v2].add(v1)
queue = deque()
for unconnected in wires:
queue.append(wires[0][0])
connected = set()
while queue:
a = queue.popleft()
connected.add(a)
for b in graph[a]:
if (a in unconnected and b in unconnected) or b in connected:
continue
connected.add(b)
queue.append(b)
answer = min(answer, abs(n - len(connected) * 2))
return answer


def test_cases():
assert (
solution(9, [[1, 3], [2, 3], [3, 4], [4, 5], [4, 6], [4, 7], [7, 8], [7, 9]])
== 3
)
assert solution(4, [[1, 2], [2, 3], [3, 4]]) == 0
assert solution(7, [[1, 2], [2, 7], [3, 7], [3, 4], [4, 5], [6, 7]]) == 1

0 comments on commit a343bfd

Please sign in to comment.