|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.IOException; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + static ArrayList<Integer>[] graph; |
| 8 | + static boolean[] visited; |
| 9 | + static StringBuilder sb = new StringBuilder(); |
| 10 | + static int N,M,V; |
| 11 | + static String[] s; |
| 12 | + |
| 13 | + public static void main(String[] args) throws IOException { |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + s = br.readLine().split(" "); |
| 16 | + N = Integer.parseInt(s[0]); //정점 개수 |
| 17 | + M = Integer.parseInt(s[1]); //간선 개수 |
| 18 | + V = Integer.parseInt(s[2]); //시작 정점 |
| 19 | + |
| 20 | + graph = new ArrayList[N + 1]; // 1-based index |
| 21 | + for (int i = 1; i <= N; i++) { |
| 22 | + graph[i] = new ArrayList<>(); |
| 23 | + } |
| 24 | + |
| 25 | + // 간선 입력 |
| 26 | + for (int i = 0; i < M; i++) { |
| 27 | + s = br.readLine().split(" "); |
| 28 | + int a = Integer.parseInt(s[0]); |
| 29 | + int b = Integer.parseInt(s[1]); |
| 30 | + graph[a].add(b); |
| 31 | + graph[b].add(a); // 양방향 그래프 |
| 32 | + } |
| 33 | + |
| 34 | + // 번호가 작은 정점부터 방문하도록 정렬 |
| 35 | + for (int i = 1; i <= N; i++) { |
| 36 | + Collections.sort(graph[i]); |
| 37 | + } |
| 38 | + |
| 39 | + // DFS 실행 |
| 40 | + visited = new boolean[N + 1]; |
| 41 | + dfs(V); |
| 42 | + sb.append("\n"); |
| 43 | + |
| 44 | + // BFS 실행 |
| 45 | + visited = new boolean[N + 1]; |
| 46 | + bfs(V); |
| 47 | + |
| 48 | + System.out.println(sb.toString()); |
| 49 | + } |
| 50 | + |
| 51 | + // DFS (재귀) |
| 52 | + static void dfs(int node) { |
| 53 | + visited[node] = true; //노드 방문 처리 |
| 54 | + sb.append(node).append(" "); |
| 55 | + |
| 56 | + for (int next : graph[node]) { //해당 노드를 기준으로 정점 선택 |
| 57 | + if (!visited[next]) { |
| 58 | + dfs(next); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // BFS (큐 사용) |
| 64 | + static void bfs(int start) { |
| 65 | + Queue<Integer> queue = new LinkedList<>(); |
| 66 | + queue.add(start); //시작 정점을 큐에 추가 |
| 67 | + visited[start] = true; //방문 처리 |
| 68 | + |
| 69 | + /* |
| 70 | + * 큐에 들어있는 모든 정점을 꺼내고 각 정점마다 연결되어있는 점들을 탐색 |
| 71 | + * */ |
| 72 | + while (!queue.isEmpty()) { |
| 73 | + int node = queue.poll(); //큐에 들어있는 원소 제거 및 반환 |
| 74 | + sb.append(node).append(" "); |
| 75 | + |
| 76 | + /* |
| 77 | + * 한 사이클이 종료되면 기준 정점에 연결되어있는 모든 정점들이 큐에 추가되어있음 |
| 78 | + * */ |
| 79 | + for (int next : graph[node]) { //헤딩 노드와 연결되어있는 정점 탐색 |
| 80 | + if (!visited[next]) { //방문하지 않았다면 방문처리하고 큐에 추가 |
| 81 | + visited[next] = true; |
| 82 | + queue.add(next); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments