728x90
SMALL
문제
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
풀이
단순히 BFS,DFS를 구현해서 출력하면 된다.
import sys
from collections import deque
def DFS(Graph, V, visited):
visited[V] =True
print(V,end=' ')
for i in Graph[V]:
if not visited[i]:
DFS(Graph,i,visited)
def BFS(Graph, start, visited):
queue=deque([start])
visited[start]=True
while queue:
V=queue.popleft()
print(V,end=' ')
for i in Graph[V]:
if not visited[i]:
queue.append(i)
visited[i]=True
if __name__ == "__main__":
N,M,V =map(int,sys.stdin.readline().split(' '))
Graph=[]
for _ in range(N+1):
Graph.append([])
for _ in range(M):
node1, node2 = map(int, sys.stdin.readline().split(' '))
Graph[node1].append(node2)
Graph[node2].append(node1)
for i in range(N+1):
Graph[i].sort()
visited = [False] * (N + 1)
DFS(Graph,V,visited)
print('')
visited = [False] * (N + 1)
BFS(Graph,V,visited)
728x90
LIST
'코테공부 > python 백준' 카테고리의 다른 글
파이썬 백준 2606번 : 바이러스 -DFS, BFS (0) | 2024.04.02 |
---|---|
파이썬 백준 2468번 : 안전 영역 (0) | 2024.04.02 |
파이썬 백준 2805번: 나무 자르기 (0) | 2024.03.29 |
파이썬 백준 2512번: 예산 (0) | 2024.03.29 |
파이썬 백준 1654번: 랜선 자르기 (0) | 2024.03.29 |