설모의 기록

[백준 1260] DFS 와 BFS 본문

알고리즘

[백준 1260] DFS 와 BFS

HA_Kwon 2017. 12. 20. 15:50

이 문제는 dfs 와 bfs 두 방식을 이용해 그래프 탐색 결과를 출력하는 문제입니다. 단 방문할 때 낮은 정점 순으로 방문을 해야 합니다.


import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { static int N, M, V; static int[][] graph; static int[] dx = { 0, -1, 0, 1 }, dy = { 1, 0, -1, 0 }; static int[] visit; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); V = Integer.parseInt(st.nextToken()); graph = new int[N + 1][N + 1]; visit = new int[N + 1]; for (int i = 1; i <= M; i++) { st = new StringTokenizer(br.readLine()); int num1 = Integer.parseInt(st.nextToken()); int num2 = Integer.parseInt(st.nextToken()); graph[num1][num2] = graph[num2][num1] = 1; } dfs(V); bfs(); } public static void dfs(int index) { visit[index] = 1; System.out.print(index + " "); for (int i = 1; i <= N; i++) { if (visit[i] != 1 && graph[index][i] == 1) { dfs(i); } } } public static void bfs() { Queue<Integer> q = new LinkedList<>(); visit = new int[N + 1]; int vertex; q.add(V); visit[V] = 1; System.out.print("\n" + V + " "); while (!q.isEmpty()) { vertex = q.poll(); for (int i = 1; i <= N; i++) { if (visit[i] != 1 && graph[vertex][i] == 1) { q.offer(i); visit[i] = 1; System.out.print(i + " "); } } } } }


'알고리즘' 카테고리의 다른 글

[백준 1003] 피보나치 함수  (0) 2018.01.01
[백준 11866] 조세퍼스 문제  (0) 2017.12.20
[백준 1966] 프린터 큐  (0) 2017.12.20
[백준 1753] 최단경로  (0) 2017.12.14
[백준 11559] Puyo Puyo  (0) 2017.12.11
Comments