[kotlin] 배열을 이용하여 그래프 알고리즘을 구현하는 방법은?
class Graph(private val numVertices: Int) {
    private val adjMatrix: Array<IntArray>

    init {
        adjMatrix = Array(numVertices) { IntArray(numVertices) }
    }

    fun addEdge(src: Int, dest: Int) {
        adjMatrix[src][dest] = 1
        adjMatrix[dest][src] = 1
    }

    fun removeEdge(src: Int, dest: Int) {
        adjMatrix[src][dest] = 0
        adjMatrix[dest][src] = 0
    }

    fun printGraph() {
        for (i in 0 until numVertices) {
            for (j in 0 until numVertices) {
                print(adjMatrix[i][j])
            }
            println()
        }
    }
}

fun main() {
    val graph = Graph(5)
    
    // 그래프에 간선 추가
    graph.addEdge(0, 1)
    graph.addEdge(0, 4)
    graph.addEdge(1, 2)
    graph.addEdge(1, 3)
    graph.addEdge(1, 4)
    graph.addEdge(2, 3)
    graph.addEdge(3, 4)
    
    // 그래프 출력
    graph.printGraph()
}

위의 코드에서는 Graph 클래스를 사용하여 그래프를 표현하고 있습니다. 그래프의 정점 수는 numVertices로 주어지며, 인접 행렬(adjMatrix)을 사용하여 간선의 존재 유무를 표시합니다. addEdge 메서드로 간선을 추가하고, removeEdge 메서드로 간선을 제거할 수 있습니다. 마지막으로, printGraph 메서드를 사용하여 그래프를 출력합니다.

위의 예제 코드를 실행하면 다음과 같은 결과가 출력됩니다:

01000
10101
01010
00101
00010

이 예제 코드는 정점의 개수가 5인 그래프를 생성하여 간선을 추가한 후, 그래프를 출력하는 방법을 보여주고 있습니다. 그래프 알고리즘을 구현할 때, 인접 행렬을 사용하는 경우 유용하게 활용할 수 있습니다.

또한, 그래프 알고리즘을 구현하는 더 다양한 방법과 개념에 관심이 있다면 아래의 Kotlin 그래프 라이브러리를 참고해보십시오: