|
| 1 | +package baekjoon.Q1260; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.Queue; |
| 8 | +import java.util.StringTokenizer; |
| 9 | + |
| 10 | +public class Main { |
| 11 | + static int N,E; |
| 12 | + static int[][] Graph; |
| 13 | + static boolean[] visited; |
| 14 | + |
| 15 | + public static void dfs(int node) { |
| 16 | + visited[node] = true; |
| 17 | + System.out.print(node + " "); |
| 18 | + |
| 19 | + for(int next = 0; next < N+1; ++next) { |
| 20 | + if(!visited[next] &&Graph[node][next] !=0) |
| 21 | + dfs(next); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public static void bfs(int node) { |
| 26 | + visited = new boolean[N+1]; |
| 27 | + |
| 28 | + Queue<Integer> myqueue = new LinkedList<>(); |
| 29 | + visited[node] = true; |
| 30 | + myqueue.add(node); |
| 31 | + |
| 32 | + while( !myqueue.isEmpty()) { |
| 33 | + int curr = myqueue.remove(); |
| 34 | + |
| 35 | + System.out.print(curr + " "); |
| 36 | + |
| 37 | + for(int next = 0; next < N+1; next++) { |
| 38 | + if(!visited[next] && Graph[curr][next] !=0) { |
| 39 | + visited[next] = true; |
| 40 | + myqueue.add(next); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public static void main(String[] args) throws IOException { |
| 47 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 48 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 49 | + |
| 50 | + N = Integer.parseInt(st.nextToken()); |
| 51 | + E = Integer.parseInt(st.nextToken()); |
| 52 | + int node = Integer.parseInt(st.nextToken()); |
| 53 | + |
| 54 | + Graph = new int[N+1][N+1]; |
| 55 | + visited = new boolean[N+1]; |
| 56 | + |
| 57 | + for(int i = 0; i < E; i++) { |
| 58 | + st = new StringTokenizer(br.readLine()); |
| 59 | + int u = Integer.parseInt(st.nextToken()); |
| 60 | + int v = Integer.parseInt(st.nextToken()); |
| 61 | + Graph[u][v] = Graph[v][u] = 1; |
| 62 | + } |
| 63 | + dfs(node); |
| 64 | + System.out.println(); |
| 65 | + bfs(node); |
| 66 | + } |
| 67 | +} |
0 commit comments