Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
Tags
- C++
- 기본클래스
- OpenCV
- 얕은복사
- 11382번
- 상속
- 데이터사이언스
- STL
- 멤버함수로구현
- 인프런
- 유도클래스
- 주피터
- 백준
- 포인터
- 깊은복사
- 코딩테스트
- OOP
- 점프투파이썬
- 참조자
- 람다식
- 스택
- 동적바인딩
- 제네릭프로그래밍
- 프로그래머스lv2
- 다형성
- c++코딩테스트합격자되기
- 연산자오버로딩
- python
- 코드잇
- list comprehension
Archives
- Today
- Total
WjExplor Story
[백준 1260번] DFS와 BFS 본문
BFS => 주위에서 읽는거, 옆으로 퍼지는 알고리즘
DFS => 한번 깊이 빠져드는거, 재귀적
그래프를 DFS와 BFS 로 출력하는 프로그램.
입력은 N(1,000까지) 엣지는 (10,000까지) 탐색을 시작할번호 V
첫줄 (예시 1 : 4 5 1 -> 4개 노드, 5개 엣지, 시작 1)
출력은
첫쨋줄 : DFS 방식 - 이동 순서 (예시 1 : 1 2 4 3) : 이진트리
다음줄에는 BFS - 이동 순서
2초 안에 계산
시간복잡도 : (V+E)
# 알고리즘 DFS, BFS
# 시간복잡도 (V+E)
import sys
from collections import deque
def DFS(cur, graph, visited):
visited[cur] = True
print(cur, end=' ')
for idx in graph[cur]:
if not visited[idx]:
DFS(idx, graph, visited)
def BFS(cur, graph, visited):
visited[cur] = True
queue = deque([cur])
while queue:
cur_node = queue.popleft()
print(cur_node, end=' ')
for idx in graph[cur_node]:
if not visited[idx]:
visited[idx] = True
queue.append(idx)
def main():
N,M,V = map(int, sys.stdin.readline().split())
graph = [ [] for _ in range(N+1)]
for i in range(M):
u,v = map(int, sys.stdin.readline().split())
graph[u].append(v)
graph[v].append(u)
# 작은것부터 정렬
for i in range(1,N+1):
graph[i].sort()
# DFS 실행
visited_dfs = [False]*(N+1)
DFS(V, graph, visited_dfs)
print()
# BFS 실행
visited_bfs = [False]*(N+1)
BFS(V, graph, visited_bfs)
if __name__ == "__main__":
main()'Python > Python : BAEKJOON' 카테고리의 다른 글
| [백준 15652] N과 M (4) (0) | 2026.03.15 |
|---|---|
| [백준 15651] N과 M (3) (0) | 2026.03.15 |
| [백준] 15650 N과 M (2) (0) | 2026.03.14 |
| [백준 1753] 최단 경로 (0) | 2026.02.20 |
| [백준] 그림 1926 (0) | 2026.01.26 |