알고리즘

  1. 출발 노드(정점) 선택
  2. 출발 노드를 기준으로 각 노드의 최소 비용 저장
  3. 방문하지 않은 노드 중 가장 비용이 적은 노드 선택
  4. 해당 노드를 거쳐 특정한 노드로 가는 경우를 고려하여 최소 비용 갱신
  5. 3 ~ 4번 반복

소스코드 - Kotlin

data class Edge(val to: Int, val weight: Int)

fun dijkstra(start: Int, graph: List<List<Edge>>, numVertices: Int): IntArray {
    val distances = IntArray(numVertices) { Int.MAX_VALUE }
    distances[start] = 0

    val pq = PriorityQueue<Pair<Int, Int>>(compareBy { it.second }) // <vertex, distance>
    pq.offer(Pair(start, 0))

    // 최단 거리 탐색
    while (pq.isNotEmpty()) { 
        // 최단 거리 짧은 정보 꺼내기
        val (currentVertex, currentDistance) = pq.poll()

        // 이미 처리된 노드
        if (distances[currentVertex] < currentDistance) continue

        // 현재 노드와 연결된 인접 노드 확인
        for (edge in graph[currentVertex]) {
            val nextDistance = currentDistance + edge.weight
            
            // 현재 노드를 거쳐 다른 도르오 이동하는 거리가 더 짧은 경우
            if (nextDistance < distances[edge.to]) {
                distances[edge.to] = nextDistance
                pq.offer(Pair(edge.to, nextDistance))
            }
        }
    }
    return distances
}

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

시간 복잡도