https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
아래는 나의 코드이다. DFS,BFS를 복습하기에 좋은 문제이다. 상하좌우를 검색하는 유형이 아닌 그래프 유형이다.
import sys
from collections import deque
N,M,V = map(int, sys.stdin.readline().split())
myMap = []
for i in range(M):
temp= list(map(int,sys.stdin.readline().split()))
myMap.append([temp[0],temp[1]])
myMap.append([temp[1],temp[0]])
myMap.sort(key= lambda x:x[1])
visited=[False]*(N+1)
DfsResult=[]
BfsResult=[]
def DFS(start):
if visited[start] == True:
return 0;
visited[start]=True
DfsResult.append(start)
for temp in myMap:
if temp[0] == start:
DFS(temp[1])
def BFS(start):
que = deque([start])
while que:
nq = que.popleft()
if visited[nq] == True:
continue
visited[nq]=True
BfsResult.append(nq)
for temp in myMap:
if temp[0] == nq:
que.append(temp[1])
DFS(V)
visited=[False]*(N+1)
BFS(V)
print(*DfsResult)
print(*BfsResult)
'Problem Solving > DFS' 카테고리의 다른 글
BOJ1941 소문난 칠공주 R * (1) | 2024.03.08 |
---|---|
음료수 얼려먹기 (0) | 2022.12.30 |
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
아래는 나의 코드이다. DFS,BFS를 복습하기에 좋은 문제이다. 상하좌우를 검색하는 유형이 아닌 그래프 유형이다.
import sys
from collections import deque
N,M,V = map(int, sys.stdin.readline().split())
myMap = []
for i in range(M):
temp= list(map(int,sys.stdin.readline().split()))
myMap.append([temp[0],temp[1]])
myMap.append([temp[1],temp[0]])
myMap.sort(key= lambda x:x[1])
visited=[False]*(N+1)
DfsResult=[]
BfsResult=[]
def DFS(start):
if visited[start] == True:
return 0;
visited[start]=True
DfsResult.append(start)
for temp in myMap:
if temp[0] == start:
DFS(temp[1])
def BFS(start):
que = deque([start])
while que:
nq = que.popleft()
if visited[nq] == True:
continue
visited[nq]=True
BfsResult.append(nq)
for temp in myMap:
if temp[0] == nq:
que.append(temp[1])
DFS(V)
visited=[False]*(N+1)
BFS(V)
print(*DfsResult)
print(*BfsResult)
'Problem Solving > DFS' 카테고리의 다른 글
BOJ1941 소문난 칠공주 R * (1) | 2024.03.08 |
---|---|
음료수 얼려먹기 (0) | 2022.12.30 |