Skip to content

Instantly share code, notes, and snippets.

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