Post

[백준/코틀린] 1260번: DFS와 BFS

실버 2

링크

1260번: DFS와 BFS

풀이

그래프를 인접 리스트로 표현하고, DFSBFS로 탐색합니다.
DFS는 스택, BFS는 큐를 사용하여 구현합니다.

코드

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
val graph = List(1001) { mutableListOf<Int>() }

fun dfs(n: Int, v: Int) = with(StringBuilder()) {
    val stack = ArrayDeque<Int>()
    val visited = BooleanArray(n + 1)

    stack.addLast(v)
    while (stack.isNotEmpty()) {
        val cur = stack.removeLast()
        if (visited[cur]) continue

        append("$cur ")
        visited[cur] = true
        graph[cur].sortedDescending().forEach {
            stack.addLast(it)
        }
    }

    println(toString())
}

fun bfs(n: Int, v: Int) = with(StringBuilder()) {
    val queue = ArrayDeque<Int>()
    val visited = BooleanArray(n + 1)

    queue.addLast(v)
    while (queue.isNotEmpty()) {
        val cur = queue.removeFirst()
        if (visited[cur]) continue

        append("$cur ")
        visited[cur] = true
        graph[cur].sorted().forEach {
            queue.addLast(it)
        }
    }

    println(toString())
}

fun main() {
    val (n, m, v) = readln().split(" ").map { it.toInt() }

    repeat(m) {
        val (a, b) = readln().split(" ").map { it.toInt() }

        graph[a] += b
        graph[b] += a
    }

    dfs(n, v)
    bfs(n, v)
}

This post is licensed under CC BY 4.0 by the author.