1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class algo2_1260_dfs_bfs { private static int N; private static int M; private static int V; private static int[][] W; private static boolean[] visit; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); N = scanner.nextInt(); M = scanner.nextInt(); V = scanner.nextInt(); W = new int[N+1][N+1]; visit = new boolean[N+1]; for(int i=0 ; i<M ; i++){ int N1 = scanner.nextInt(); int N2 = scanner.nextInt(); W[N1][N2] = 1; W[N2][N1] = 1; } scanner.close(); dfs(V); System.out.print("\n"); for(int i=0 ; i<visit.length ; i++) visit[i] = false; bfs(V); } public static void dfs(int num){ System.out.print(num + " "); visit[num] = true; for(int i=1 ; i<=N ; i++){ if(W[num][i]==1 && !visit[i]) dfs(i); } } public static void bfs(int num){ Queue<Integer> queue = new LinkedList<>(); queue.offer(num); visit[num] = true; while(!queue.isEmpty()){ int front = (int)queue.peek(); queue.poll(); System.out.print(front + " "); for(int i=1 ; i<=N ; i++){ if(W[front][i]==1 && !visit[i]){ queue.offer(i); visit[i] = true; } } } } } | cs |
'Algorithm' 카테고리의 다른 글
백준 9012번: 괄호 (0) | 2018.07.18 |
---|---|
백준 10828번: 스택 (0) | 2018.07.17 |
BFS (Breadth-First Search) (0) | 2018.04.12 |
DFS (Depth-First Search) (0) | 2018.04.12 |
백준 1003번: 피보나치 함수 (0) | 2018.04.10 |