알고리즘

소스코드 - Kotlin

fun main() {
    // 노드가 연결된 간선
    val graph = mapOf(
        1 to listOf(2, 3, 4),
        2 to listOf(1, 4),
        3 to listOf(1, 4),
        4 to listOf(1, 2, 3)
    )
    println("stack : ${dfsWithStack(1, graph)}") // 1, 2, 4, 3
    println("recursive : ${dfsWithRecursion(1, graph)}") // 1, 2, 4, 3
}

// 스택
fun dfsWithStack(start: Int, graph: Map<Int, List<Int>>) {
    val visited = mutableSetOf<Int>()
    val stack = Stack<Int>()

    stack.push(start)

    while (stack.isNotEmpty()) {
        val node = stack.pop()
        if (node !in visited) {
            println(node)
            visited.add(node)
            graph[node]?.reversed()?.forEach { 
                if (it !in visited) {
                    stack.push(it)
                }
            }
        }
    }
}

// 재귀
fun dfsWithRecursion(node: Int, graph: Map<Int, List<Int>>, visited: MutableSet<Int> = mutableSetOf()) {
    if (node in visited) return
    println(node)
    visited.add(node)
    graph[node]?.forEach { dfsWithRecursion(it, graph, visited) }
}

범위 및 함수 사용시 유의사항

장점

단점

시간 복잡도