https://www.acmicpc.net/problem/1260
import java.util.*;
import java.io.*;
public class Main
{
static List<Integer>[] graph;
static List<Integer> ans_dfs;
static List<Integer> ans_bfs;
static boolean[] visited_dfs;
static boolean[] visited_bfs;
public static void dfs(int node){
if(visited_dfs[node]) return;
ans_dfs.add(node);
visited_dfs[node] = true;
Collections.sort(graph[node]);
for(int next: graph[node]){
dfs(next);
}
return;
}
public static void bfs(int start){
Queue<Integer> q = new LinkedList();
q.add(start);
while(q.size()>0){
int node = q.poll();
if(visited_bfs[node]) continue;
ans_bfs.add(node);
visited_bfs[node] = true;
Collections.sort(graph[node]);
for(int n: graph[node]){
if(!visited_bfs[n]) q.add(n);
}
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int n = Integer.parseInt(input[0]);
int m = Integer.parseInt(input[1]);
int v = Integer.parseInt(input[2]);
visited_bfs = new boolean[n+1];
visited_dfs = new boolean[n+1];
ans_bfs = new ArrayList();
ans_dfs = new ArrayList();
Arrays.fill(visited_dfs,false);
Arrays.fill(visited_bfs,false);
graph = new List[n+1];
for(int i=0; i<n+1;i++){
graph[i] = new ArrayList<Integer>();
}
for(int i = 0; i<m; i++){
String[] temp = br.readLine().split(" ");
int start = Integer.parseInt(temp[0]);
int end = Integer.parseInt(temp[1]);
graph[start].add(end);
graph[end].add(start);
}
dfs(v);
bfs(v);
System.out.println(ans_dfs.toString().replace("[","").replace("]","").replace(",",""));
System.out.println(ans_bfs.toString().replace("[","").replace("]","").replace(",",""));
}
}
'Problem Solving > BFS' 카테고리의 다른 글
BOJ2606 바이러스 (1) | 2024.03.07 |
---|---|
BOJ11724 연결 요소의 개수 (1) | 2024.03.07 |
BOJ1389 케빈 베이컨의 6단계 법칙 (0) | 2023.03.29 |
BOJ1012 유기농 배추 (0) | 2023.03.14 |
미로 탈출 (0) | 2023.01.02 |