문제
https://www.acmicpc.net/problem/1707
1707번: 이분 그래프
입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V와 간선의 개수 E가 빈 칸을 사이에
www.acmicpc.net
코드
import sys
from collections import deque
input=sys.stdin.readline
t=int(input())
for _ in range(t):
v,e=map(int,input().split())
visited=[0]*(v+1)
graph=[[] for _ in range(v+1)]
for _ in range(e):
a,b=map(int,input().split())
graph[a].append(b)
graph[b].append(a)
queue=deque()
group=1
result=True
for i in range(1,v+1):
if visited[i]==0:
queue.append(i)
visited[i]=group
while queue:
p=queue.popleft()
for j in graph[p]:
if visited[j]==0:
queue.append(j)
visited[j]=-1*visited[p]
else:
if visited[j]==visited[p]:
result=False
if result:
print("YES")
else:
print("NO")
이분 그래프(Bipartite Graph)란
인접한 정점끼리 서로 다른 색으로 칠해서 모든 정점을 두 가지 색으로만 칠할 수 있는 그래프
'문제풀이 > DFS & BFS' 카테고리의 다른 글
[PyPy] [DFS] 백준 15684 사다리 조작 (0) | 2022.05.19 |
---|---|
[파이썬] [DFS] 백준 14500 테트로미노 (0) | 2022.05.15 |
[파이썬] [DFS] 백준 1068 트리 (0) | 2022.05.11 |
[PyPy] [DFS] 백준 2580 스도쿠 (0) | 2022.05.05 |
[파이썬] [DFS] 백준 1987 알파벳 (0) | 2022.05.02 |