-
[백준] 1260번_DFS와BFSStudy/알고리즘 2020. 2. 20. 00:52
문제 링크 : https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
www.acmicpc.net
from collections import deque #인접리스트 활용 N,M,V = map(int,input().split()) adjacent = [[] for _ in range(N+1)] for _ in range(M): s,e = map(int,input().split()) adjacent[s].append(e) adjacent[e].append(s) for i in range(len(adjacent)): adjacent[i] = sorted(adjacent[i]) # dfs check = [False for _ in range(N+1)] check[0] = True def dfs(x): check[x] = True print(x,end=" ") for i in range(len(adjacent[x])): y = adjacent[x][i] if not check[y]: dfs(y) dfs(V) print() # bfs def bfs(x): queue = deque() check = [False for _ in range(N+1)] check[0] = True; check[V] = True queue.append(V) while queue: x = queue.popleft() print(x,end=" ") for i in range(len(adjacent[x])): y = adjacent[x][i] if not check[y]: check[y] = True queue.append(y) bfs(V)
'Study > 알고리즘' 카테고리의 다른 글
[백준] 4963번_섬의개수 (0) 2020.02.21 [백준] 11724번_연결요소의개수 (0) 2020.02.20 [백준] 1138번_한줄로서기 (0) 2020.02.19 [백준] 14500번_테트로미노 (0) 2020.02.15 [백준] 1476번_날짜계산 (0) 2020.02.15