import java.util.*;
public class Main {
public static boolean[] dfsVisited;
public static boolean[] bfsVisited;
public static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
public static void dfs(int start) {
dfsVisited[start] = true;
System.out.print(start + " ");
for (int i = 0; i < graph.get(start).size(); i++) {
int x = graph.get(start).get(i);
if (!dfsVisited[x]) dfs(x);
}
}
public static void bfs(int start) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(start);
bfsVisited[start] = true;
while (!queue.isEmpty()) {
int x = queue.poll();
System.out.print(x + " ");
for (int i = 0; i < graph.get(x).size(); i++) {
int y = graph.get(x).get(i);
if (!bfsVisited[y]) {
queue.offer(y);
bfsVisited[y] = true;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int start = sc.nextInt();
dfsVisited = new boolean[n + 1];
bfsVisited = new boolean[n + 1];
for (int i = 0; i < n + 1; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
graph.get(a).add(b);
graph.get(b).add(a);
}
for (int i = 1; i < n + 1; i++) {
Collections.sort(graph.get(i));
}
dfs(start);
System.out.println();
bfs(start);
}
}
728x90
반응형
'Algorithm' 카테고리의 다른 글
[Algorithm] 삽입정렬 (0) | 2021.11.26 |
---|---|
[Algorithm] 선택정렬 (0) | 2021.11.26 |
[Algorithm] Vector (0) | 2021.10.06 |
[Algorithm] Stack (0) | 2021.09.21 |
[Algorithm] BOJ 1158 (0) | 2021.07.28 |
댓글