๋จผ์ 13023๋ฒ์ ํ๊ธฐ ์ ์ 1260๋ฒ ํ์ด๋ฅผ ์ฒจ๋ถํ๋ค!
DFS์ BFS๋ฅผ ๊ตฌํํ์ฌ ์ถ๋ ฅํ๋ ๋ฌธ์ ์ด๋ค.
# DFS์ BFS
import sys
from collections import deque
input = sys.stdin.readline
N, M, V = map(int, input().split())
graph = [[] for _ in range(N+1)]
visited = [0] * (N+1) # dfs
visited2 = [0] * (N+1) # bfs
for i in range(M):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
# ๋ฐฉ๋ฌธํ ์ ์๋ ์ ์ ์ด ์ฌ๋ฌ๊ฐ์ธ ๊ฒฝ์ฐ ์ ์ ๋ฒํธ๊ฐ ์์ ๊ฒ์ ๋จผ์ ๋ฐฉ๋ฌธํ๋ค
for i in graph:
i.sort()
# print(graph)
def dfs(graph, start, visited):
visited[start] = True
print(start, end=' ')
for i in graph[start]:
if not visited[i]:
dfs(graph, i, visited)
def bfs(graph, start, visited):
q = deque([start])
visited[start] = True
while q:
v = q.popleft()
print(v, end=' ')
for i in graph[v]:
if not visited[i]:
q.append(i)
visited[i] = True
dfs(graph, V, visited)
print()
bfs(graph, V, visited2)
์ค๋์ ๋ค์๊ณผ ๊ฐ์ ์น๊ตฌ ๊ด๊ณ๋ฅผ ๊ฐ์ง ์ฌ๋ A, B, C, D, E๊ฐ ์กด์ฌํ๋์ง ๊ตฌํด๋ณด๋ ค๊ณ ํ๋ค.
- A๋ B์ ์น๊ตฌ๋ค.
- B๋ C์ ์น๊ตฌ๋ค.
- C๋ D์ ์น๊ตฌ๋ค.
- D๋ E์ ์น๊ตฌ๋ค.
์ฌ์ดํด์ด ์กด์ฌํ๋ ๊ทธ๋ํ
๋ผ๊ณ ์ดํดํ์ผ๋ ๊น์ด๊ฐ 4๋ณด๋ค ๊น์ผ๋ฉด 1์ ๋ฐํํด์ฃผ๋ฉด ๋๋ค๋ ๋ป์ด์๋ค..!visited[start] = False
๋ฅผ ์ถ๊ฐํด์ฃผ์๋ค.# ABCDE
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
graph = [[] for _ in range(N+1)]
visited = [0] * (N+1)
answer = False
for _ in range(M):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
def dfs(graph, start, visited, depth):
global answer
visited[start] = True
# ๊น์ด๊ฐ 5๋ฉด True ๋ฐํ
if depth == 5:
answer = True
return
for i in graph[start]:
if not visited[i]:
dfs(graph, i, visited, depth+1)
visited[start] = False
for i in range(N):
dfs(graph, i, visited, 1)
if answer:
break
if answer:
print(1)
else:
print(0)