💬 문제
문제 난이도: 백준 골드 4
❗️접근 방법
- 이분 그래프란?
그래프의 인접한 노드에 다른 색을 칠하려고 할 때, 단 2가지의 색만으로도 칠할 수 있는 그래프.
-> 이분 그래프에서는 노드들을 두 그룹으로 나눌 때 같은 그룹에 있는 노드끼리는 인접하지 않아야 한다.
- dfs를 활용해서 인접한 노드간에 색을 비교한다.
- 비연결 리스트 또한 이분 그래프가 될 수 있기 때문에 for문을 돌며 모든 노드에 대한 색을 비교한다.
✅ 정답 코드
import sys
from collections import defaultdict
input = sys.stdin.readline
print = sys.stdout.write
sys.setrecursionlimit(10 ** 9)
def dfs(start, color):
global flag
if colors[start] == 0:
colors[start] = color
for next in nodes[start]:
if colors[next] != 0:
if colors[next] == colors[start]:
flag = False
return
else:
dfs(next, color*-1)
N = int(input())
for _ in range(N):
V, E = map(int, input().split(' '))
nodes = defaultdict(list)
colors = [0 for _ in range(V+1)]
flag = True
for _ in range(E):
start, end = map(int, input().split(' '))
nodes[start].append(end)
nodes[end].append(start)
for key in nodes:
dfs(key, 1)
if flag:
print('YES\n')
else:
print('NO\n')
✍️ 새롭게 배운 부분
- 비연결 리스트여도 이분 그래프일 수 있으므로, 모든 노드에 대한 dfs를 실행해주기 위한 for문이 필요하다.
- colors라는 리스트를 통해 색 비교뿐만 아니라 방문한 적이 있는지(visited)도 한번에 확인할 수 있다.