https://www.acmicpc.net/problem/1260
- ์ธ์ ๋ฆฌ์คํธ๋ฅผ ์ด์ฉํด์ ์ ์ ์ ๋ฐฉ๋ฌธ์ฌ๋ถ๋ฅผ ์ฒดํฌํ๋ค. (์
๋ ฅ์์)
- 1 2 ์ ๋ ฅ -> graph = [ [ ], [2], [1], [ ] , [ ] ]
- 1 3 ์ ๋ ฅ -> graph = [ [ ], [2, 3], [1], [1] , [ ] ]
- 1 4 ์ ๋ ฅ - > graph = [ [ ], [2, 3, 4], [1], [1] , [1] ]
- 2 4 ์ ๋ ฅ - > graph = [ [ ], [2, 3, 4], [1, 4], [1] , [1, 2] ]
- 3 4 ์ ๋ ฅ -> graph = [ [ ], [2, 3, 4], [1, 4], [1, 4] , [1, 2, 3] ]
- ์์์ ํ์๋ ์๊ณ ๋ฆฌ์ฆ ์์ 1,2์ ์ ์ฌํจ.
ํ์ด
import java.io.*;
import java.util.*;
public class Main{
static boolean[] visited;
static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
static ArrayList<Integer> dfsList = new ArrayList<>();
static ArrayList<Integer> bfsList = new ArrayList<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
int N = Integer.parseInt(str[0]);
int M = Integer.parseInt(str[1]);
int V = Integer.parseInt(str[2]);
//graph ์ด๊ธฐํ
for(int i=0; i<=N; i++){
graph.add(new ArrayList<>());
}
//graph์ ๊ฐ์ ์
๋ ฅ
for(int i=0; i<M; i++){
str = br.readLine().split(" ");
int u = Integer.parseInt(str[0]);
int v = Integer.parseInt(str[1]);
//์๋ฐฉํฅ
graph.get(u).add(v);
graph.get(v).add(u);
}
//์ค๋ฆ์ฐจ์ ๋ฐฉ๋ฌธ
for(int i=1; i<=N; i++){
Collections.sort(graph.get(i));
}
//DFS
visited = new boolean[N+1];
dfs(V);
//BFS
visited = new boolean[N+1];
bfs(V);
//์ถ๋ ฅ
for(int node : dfsList){
System.out.print(node + " ");
}
System.out.println();
for(int node : bfsList){
System.out.print(node + " ");
}
}
//DFS ํ์
private static void dfs(int node){
visited[node] = true;
dfsList.add(node);
for(int nextNode : graph.get(node)){
if(!visited[nextNode]){
dfs(nextNode);
}
}
}
//BFS ํ์
private static void bfs(int start){
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = true;
while(!queue.isEmpty()){
int current = queue.poll();
bfsList.add(current);
for(int nextNode : graph.get(current)){
if(!visited[nextNode]){
visited[nextNode] = true;
queue.add(nextNode);
}
}
}
}
}
'Algorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Silver II/JAVA] 2210 ์ซ์ํ ์ ํ (0) | 2024.12.12 |
---|---|
[Silver IV/JAVA] 1388 ๋ฐ๋ฅ์ฅ์ (2) | 2024.12.10 |
[Silver II/JAVA] 24479, 24480 ์๊ณ ๋ฆฌ์ฆ ์์ - ๊น์ด ์ฐ์ ํ์ 1, 2 (0) | 2024.12.01 |
[Silver III/JAVA] 10451 ์์ด ์ฌ์ดํด (0) | 2024.11.23 |
[Silver V/JAVA] 13241 ์ต์๊ณต๋ฐฐ์ (0) | 2024.11.22 |