/24444_알고리즘 수업 - 너비 우선 탐색 1.swift Secret
Created
November 1, 2024 13:50
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let input = readLine()!.split { $0 == " " }.map { Int($0)! } | |
let n = input[0], m = input[1], r = input[2] | |
var graph = [[Int]](repeating: [], count: n + 1) | |
var visited = [Int](repeating: 0, count: n + 1) | |
for _ in 0..<m { | |
let input = readLine()!.split { $0 == " " }.map { Int($0)! } | |
let a = input[0], b = input[1] | |
graph[a].append(b) | |
graph[b].append(a) | |
} | |
for i in 1...n { graph[i] = graph[i].sorted(by: <) } | |
var queue = [r] | |
var index = 0 | |
var order = 1 | |
visited[r] = 1 | |
while queue.count > index { | |
let currentNode = queue[index] | |
for nextNode in graph[currentNode] { | |
if visited[nextNode] == 0 { | |
order += 1 | |
visited[nextNode] = order | |
queue.append((nextNode)) | |
} | |
} | |
index += 1 | |
} | |
print(visited[1...].map { String($0) }.joined(separator: "\n")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment