티스토리 뷰

문제


코드

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class Main {

	static ArrayList[] a;
	static boolean[] c;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] input = br.readLine().split(" ");
		int n = Integer.parseInt(input[0]); // 정점
		int m = Integer.parseInt(input[1]); // 간선
		int start_v = Integer.parseInt(input[2]); // 정점의 번호

		a = (ArrayList[]) new ArrayList[n + 1];
		for (int i = 1; i < n + 1; i++) {
			a[i] = new ArrayList<>();
		}

		for (int i = 0; i < m; i++) {
			String[] uv = br.readLine().split(" ");
			int u = Integer.parseInt(uv[0]);
			int v = Integer.parseInt(uv[1]);
			a[u].add(v);
			a[v].add(u);
		}

		for (int i = 1; i < n + 1; i++) {
			Collections.sort(a[i]);
		}

		c = new boolean[n + 1];
		dfs(start_v);
		System.out.println("");

		c = new boolean[n + 1];
		bfs(start_v);
	}

	public static void dfs(int x) {
		if (c[x]) {
			return;
		}

		c[x] = true;
		System.out.print(x + " ");
		for (int y : a[x]) {
			if (c[y] == false) {
				dfs(y);
			}
		}
	}

	public static void bfs(int start) {
		Queue q = new LinkedList<>();
		q.add(start);
		c[start] = true;

		while (!q.isEmpty()) {
			int x = q.remove();
			System.out.print(x + " ");
			for (int y : a[x]) {
				if (c[y] == false) {
					c[y] = true;
					q.add(y);
				}
			}
		}
	}

}

출처


https://www.acmicpc.net/problem/1260


'알고리즘 > 백준알고리즘(JAVA)' 카테고리의 다른 글

#2609번 : 최대공약수와 최소공배수  (0) 2018.11.04
#10430번 : 나머지  (0) 2018.11.04
#2743번 : 단어 길이 재기  (0) 2018.09.26
#1158번 : 조세퍼스 문제  (0) 2018.09.25
#1406번 : 에디터  (0) 2018.09.19
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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
글 보관함