Skip to content

Commit

Permalink
[Silver II] Title: DFS와 BFS, Time: 124 ms, Memory: 34096 KB -BaekjoonHub
Browse files Browse the repository at this point in the history
  • Loading branch information
alswo1212 committed Aug 17, 2024
1 parent 3360d5e commit c83ad6c
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
60 changes: 60 additions & 0 deletions 백준/Silver/1260. DFS와 BFS/DFS와 BFS.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import sys
from collections import deque
N, M, V = map(int,sys.stdin.readline().split())

num_dict = {}

for _ in range(M):
num1, num2 = map(int, sys.stdin.readline().split())
if num1 not in num_dict:
num_dict[num1] = {
'dfs_used' : False,
'bfs_used' : False,
'link' : []
}
num_dict[num1]['link'].append(num2)

if num2 not in num_dict:
num_dict[num2] = {
'dfs_used' : False,
'bfs_used' : False,
'link' : []
}
num_dict[num2]['link'].append(num1)

stack = [V]
dfs_result = []
while stack:
poped = stack.pop()
if poped not in num_dict:
dfs_result.append(poped)
continue

if not num_dict[poped]['dfs_used']:
dfs_result.append(poped)
num_dict[poped]['dfs_used'] = True

num_dict[poped]['link'].sort()
for num in num_dict[poped]['link'][::-1]:
if num_dict[num]['dfs_used'] : continue
stack.append(num)

print(*dfs_result)

q = deque([V])
bfs_result = []
while q:
polled = q.popleft()
if polled not in num_dict:
bfs_result.append(polled)
continue

if not num_dict[polled]['bfs_used']:
bfs_result.append(polled)
num_dict[polled]['bfs_used'] = True

for num in num_dict[polled]['link']:
if num_dict[num]['bfs_used']: continue
q.append(num)

print(*bfs_result)
28 changes: 28 additions & 0 deletions 백준/Silver/1260. DFS와 BFS/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# [Silver II] DFS와 BFS - 1260

[문제 링크](https://www.acmicpc.net/problem/1260)

### 성능 요약

메모리: 34096 KB, 시간: 124 ms

### 분류

그래프 이론, 그래프 탐색, 너비 우선 탐색, 깊이 우선 탐색

### 제출 일자

2024년 8월 17일 16:42:37

### 문제 설명

<p>그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.</p>

### 입력

<p>첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.</p>

### 출력

<p>첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.</p>

0 comments on commit c83ad6c

Please sign in to comment.