본문 바로가기
알고리즘

Swift로 알고리즘 그래프 구현하기

by mr.conan 2023. 6. 27.
728x90
반응형

안녕하세요! 이번에는 Swift 언어를 사용하여 알고리즘 그래프를 구현하는 예시를 알려드리려고 합니다. 그래프는 정점(Vertex)과 간선(Edge)으로 구성되는 자료구조로, 여러 개의 객체들이 연결된 형태를 나타냅니다.

 

그래프 구조 정의하기 우선, 그래프 구조를 정의하기 위해 Vertex와 Edge를 표현하는 클래스를 작성합니다

class Vertex<T> {
    var value: T
    var edges: [Edge<T>]
    
    init(value: T) {
        self.value = value
        self.edges = []
    }
}

class Edge<T> {
    var source: Vertex<T>
    var destination: Vertex<T>
    var weight: Double?
    
    init(source: Vertex<T>, destination: Vertex<T>, weight: Double? = nil) {
        self.source = source
        self.destination = destination
        self.weight = weight
    }
}

그래프 클래스 작성하기 이제 그래프를 표현하는 Graph 클래스를 작성합니다. Graph 클래스는 Vertex들을 저장하고, 간선을 연결하는 기능을 제공합니다.

 

class Graph<T> {
    var vertices: [Vertex<T>]
    
    init() {
        self.vertices = []
    }
    
    func addVertex(value: T) -> Vertex<T> {
        let vertex = Vertex(value: value)
        vertices.append(vertex)
        return vertex
    }
    
    func addEdge(source: Vertex<T>, destination: Vertex<T>, weight: Double? = nil) {
        let edge = Edge(source: source, destination: destination, weight: weight)
        source.edges.append(edge)
    }
}

그래프 구현 및 활용 예시 이제 위에서 작성한 Graph 클래스를 사용하여 그래프를 구현하고 활용해보겠습니다.

// 그래프 인스턴스 생성
let graph = Graph<Int>()

// 정점 추가
let vertex1 = graph.addVertex(value: 1)
let vertex2 = graph.addVertex(value: 2)
let vertex3 = graph.addVertex(value: 3)

// 간선 추가
graph.addEdge(source: vertex1, destination: vertex2)
graph.addEdge(source: vertex2, destination: vertex3)
graph.addEdge(source: vertex3, destination: vertex1)

// 그래프 탐색
for vertex in graph.vertices {
    print("정점 \(vertex.value)에 연결된 간선:")
    for edge in vertex.edges {
        print("\(edge.source.value) -> \(edge.destination.value)")
    }
    print()
}

이와 같이 Swift 언어를 사용하여 그래프를 구현하고 활용할 수 있습니다. 그래프를 표현하는 클래스를 정의하고, 정점과 간선을 추가하여 원하는 그래프를 생성할 수 있습니다. 그래프의 탐색이나 다양한 알고리즘 구현에 활용할 수 있으니, 유연하게 활용해보세요!

728x90
반응형