https://www.acmicpc.net/problem/1260
제출 코드--------------------------------------------------------------------------------------------------------------------------------------
def dfs(v):
print(v, end=' ')
visit[v]=1
for i in range(1, n+1):
if visit[i]==0 and graph[v][i]==1:
dfs(i)
def bfs(v):
queue=[v]
visit[v]=0
while queue:
v=queue[0]
print(v, end=' ')
del queue[0]
for i in range(1, n+1):
if visit[i]==1 and graph[v][i]==1:
queue.append(i)
visit[i]=0
n,m,v=map(int,input().split())
graph =[[0]*(n+1) for _ in range(n+1)]
visit=[0]*(n+1)
for i in range(m):
x,y=map(int,input().split())
graph[x][y]=1
graph[y][x]=1
dfs(v)
print()
bfs(v)
참고코드---------------------------------------------------------------------------------------------------------------------------------------
#1
def dfs(v):
print(v, end=' ')
visit[v] = 1
for i in range(1, n + 1):
if visit[i] == 0 and s[v][i] == 1:
dfs(i)
def bfs(v):
queue = [v]
visit[v] = 0
while(queue):
v = queue[0]
print(v, end=' ')
del queue[0]
for i in range(1, n + 1):
if visit[i] == 1 and s[v][i] == 1:
queue.append(i)
visit[i] = 0
n, m, v = map(int, input().split())
s = [[0] * (n + 1) for i in range(n + 1)]
visit = [0 for i in range(n + 1)]
for i in range(m):
x, y = map(int, input().split())
s[x][y] = 1
s[y][x] = 1
dfs(v)
print()
bfs(v)
#2
from collections import deque
import sys
read = sys.stdin.readline
def bfs(v):
q = deque()
q.append(v)
visit_list[v] = 1
while q:
v = q.popleft()
print(v, end = " ")
for i in range(1, n + 1):
if visit_list[i] == 0 and graph[v][i] == 1:
q.append(i)
visit_list[i] = 1
def dfs(v):
visit_list2[v] = 1
print(v, end = " ")
for i in range(1, n + 1):
if visit_list2[i] == 0 and graph[v][i] == 1:
dfs(i)
n, m, v = map(int, read().split())
graph = [[0] * (n + 1) for _ in range(n + 1)]
visit_list = [0] * (n + 1)
visit_list2 = [0] * (n + 1)
for _ in range(m):
a, b = map(int, read().split())
graph[a][b] = graph[b][a] = 1
dfs(v)
print()
bfs(v)
'파이썬알고리즘' 카테고리의 다른 글
20210808#(75) 백준 문자열문제풀이(백준 6문제) (0) | 2021.08.08 |
---|---|
20210806#(74) 백준 2267번 단지번호붙이기 (dfs,bfs) (0) | 2021.08.06 |
20210805#(72) 이코테 미로탈출 DFS/BFS (0) | 2021.08.05 |
20210804#(71) DFS/BFS 개념 (0) | 2021.08.04 |
20210802#(70) 개미 전사 (DP) (0) | 2021.08.02 |