๋ฌธ์
DFS์ BFS
ํ์ด
import java.util.*;
class Main {
static int n;
static int m;
static int v;
static boolean[] visited;
static ArrayList<ArrayList<Integer>> graph;
static void dfs(int x) {
visited[x] = true;
System.out.print(x + " ");
for(int next : graph.get(x)) {
if(!visited[next]) {
visited[next] = true;
dfs(next);
}
}
}
static void bfs(int start) {
Queue<Integer> q = new LinkedList<>();
q.offer(start);
visited[start] = true;
while(!q.isEmpty()) {
int x = q.poll();
System.out.print(x + " ");
for(int next : graph.get(x)) {
if(!visited[next]) {
q.offer(next);
visited[next] = true;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
v = sc.nextInt();
visited = new boolean[n + 1];
// ๊ทธ๋ํ ๋ง๋ค๊ธฐ
graph = new ArrayList<>();
for(int i = 0; i <= n; i++) {
graph.add(new ArrayList<Integer>());
}
for(int i = 0; i < m; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
// ๊ทธ๋ํ ์ ๋ ฌํ๊ธฐ
for(int i = 0; i < graph.size(); i++) {
Collections.sort(graph.get(i));
}
dfs(v);
System.out.println("");
visited = new boolean[n + 1];
bfs(v);
}
}
- dfs๋ ์ฌ๊ทํจ์, bfs๋ ํ๋ก ๊ตฌํํฉ๋๋ค.
- ๊ณ์ ํธ๋๊น ์ด์ ์ต์ํด์ง๋ ๋๋..