새소식

Algorithm

BFS

  • -

Swift

// https://school.programmers.co.kr/learn/courses/30/lessons/49189
import Foundation

func bfs(n: Int, graph: [Int: [Int: Int]], beginnigNode: Int, visit: (_ node: Int, _ distance: Int) -> Void) {
    var queue = [(Int, Int)]()
    var visited = [Bool](repeating: false, count: n)
    queue.append((beginnigNode, 0))
    visited[beginnigNode - 1] = true
    
    while !queue.isEmpty {
        let (visitingNode, distance) = queue.removeFirst()
        visit(visitingNode, distance)
        
        graph[visitingNode]?.forEach { adjacentNode, adjacentDistance in
            guard !visited[adjacentNode - 1] else { return }
            queue.append((adjacentNode, distance + adjacentDistance))
            visited[adjacentNode - 1] = true
        }
    }
}

func solution(_ n: Int, _ edges: [[Int]]) -> Int {
    var graph = [Int: [Int: Int]]()
    edges.forEach { edge in
        if graph[edge[0]] == nil {
            graph[edge[0]] = [:]
        }
        graph[edge[0]]![edge[1]] = 1
        if graph[edge[1]] == nil {
            graph[edge[1]] = [:]
        }
        graph[edge[1]]![edge[0]] = 1
    }
    var maxDistance = 0
    var answer = 0
    bfs(n: n, graph: graph, beginnigNode: 1) { node, distance in
        print("visiting \(node), (\(distance))")
        if maxDistance < distance {
            maxDistance = distance
            answer = 1
        } else if maxDistance == distance {
            answer += 1
        }
    }
    return answer
}

#if RANDOM
let n = Int.random(in: 2...20000)
let edgeCount = Int.random(in: 1...50000)
var edgeset: Set<[Int]> = []
for _ in 0..<edgeCount {
    var a = 0
    var b = 0
    while edgeset.contains([a, b]) || a == b {
        a = Int.random(in: 1...n)
        b = Int.random(in: 1...n)
    }
    edgeset.insert([a, b])
}
let edges = edgeset.map { $0 }
#else
let n = 6
let edges = [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]
#endif

print("입력값: n = \(n)")
print("edges = \(edges)")
print(solution(n, edges))

 

반응형

'Algorithm' 카테고리의 다른 글

DFS와 BFS  (0) 2023.11.09
퀵소트  (0) 2023.08.03
다익스트라  (0) 2019.06.20
최소 스패닝 트리  (0) 2019.06.20
인덱스 트리  (0) 2019.06.20
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.