DFS와 BFS (백준 1260)
2023. 1. 10. 15:11
2초 | 128 MB |
문제
그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
입력
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
출력
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
<생각의 흐름>
인접리스트로 그래프를 표현한다음 정렬을 해줘야함
(인접 행렬로 표현해주면 더 간단)
bfs랑 dfs는 늘 하던대로 별 차이 없음
<코드>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
static int N,M;
static boolean[] visiteddfs;
static boolean[] visitedbfs;
static ArrayList<ArrayList<Integer>> A = new ArrayList<ArrayList<Integer>>();;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
for(int i=0; i<N+1; i++) {
A.add(new ArrayList<Integer>());
}
int start = Integer.parseInt(st.nextToken());
visitedbfs = new boolean[N+1];
visiteddfs = new boolean[N+1];
for(int i = 0 ; i < M ; i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
A.get(a).add(b);
A.get(b).add(a);
}
for(int i=0; i<N+1; i++) {
Collections.sort(A.get(i));
}
DFS(start);
System.out.print("\n");
BFS(start);
}
private static void BFS(int start) {
Queue<Integer> q = new LinkedList<>();
q.offer(start);
visitedbfs[start]=true;
while(!q.isEmpty()){
int now = q.poll();
System.out.print(now+" ");
for(int i : A.get(now)){ // 작은거 부터
if(!visitedbfs[i]){
q.offer(i);
visitedbfs[i]=true;
}
}
}
}
private static void DFS(int start) {
if(visiteddfs[start]) return; // 이미 방문한 곳이면
visiteddfs[start]=true;
System.out.print(start+" ");
//방문 안한곳이면
for(int i : A.get(start)){ // 여기서 제일 작은 값을 고르기
if(!visiteddfs[i]){
DFS(i);
}
}
}
}
<피드백>
BFS나 DFS 문제나오면 자동으로 이러한 구조로 짤수있도록 연습!!
'코테뿌수기 - java > 문제 풀기' 카테고리의 다른 글
유기농 배추 (백준 1012) (0) | 2023.01.11 |
---|---|
숨바꼭질 (백준 1697) (0) | 2023.01.11 |
2 x n 타일링 (백준 11726) (0) | 2023.01.08 |
이항 계수 1 (백준 11050) (0) | 2023.01.07 |
줄 세우기 (백준 2252) (0) | 2023.01.04 |