백준 - DFS와 BFS [1260]

노력하는 배짱이·2021년 3월 2일
0
post-thumbnail

문제

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.

입력

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

출력

첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

풀이

dfs 와 bfs 각각 구현해서 출력하면 되는 문제이다. 다만 문제의 조건으로 정점 번호가 작은 것부터 방문하라는 것이 주어져 정렬을 한번 해주어야 한다.

이중 ArrayList로 구현했기 때문에 정점의 개수만큼 for문을 돌려 정렬을 수행하고, dfs 를 먼저 수행한 뒤 visited 배열을 다시 false로 채워주는 과정이 필요하다.

소스

import java.util.*;

public class Main {
	public static int n, m;
	public static boolean[] visited = new boolean[1001];

	public static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();

	public static void dfs(int x) {
		visited[x] = true;
		System.out.print(x + " ");

		for (int i = 0; i < graph.get(x).size(); i++) {
			int y = graph.get(x).get(i);
			if (!visited[y]) {
				dfs(y);
			}
		}

	}

	public static void bfs(int x) {
		Queue<Integer> q = new LinkedList<Integer>();

		q.offer(x);
		visited[x] = true;

		while (!q.isEmpty()) {
			int now = q.poll();
			System.out.print(now + " ");

			for (int i = 0; i < graph.get(now).size(); i++) {
				int y = graph.get(now).get(i);
				if (!visited[y]) {
					q.offer(y);
					visited[y] = true;
				}
			}
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		n = sc.nextInt();
		m = sc.nextInt();
		int start = sc.nextInt();

		for (int i = 0; i <= n; i++) {
			graph.add(new ArrayList<Integer>());
		}

		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 = 0; i <= n; i++) {
			Collections.sort(graph.get(i));
		}

		dfs(start);
		System.out.println();
		Arrays.fill(visited, false);
		bfs(start);

	}

}

0개의 댓글

관련 채용 정보