Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sprint6.tasks.F
- import java.io.BufferedReader
- import java.io.InputStreamReader
- import java.util.*
- typealias Edges = Map<Int, List<Int>>
- fun main() {
- val buffer = BufferedReader(InputStreamReader(System.`in`))
- val edges = readGraph(buffer, true)
- buffer.readLine().split(" ").map { it.toInt() }
- .let { println(edges.bfs(it[0], it[1])) }
- }
- fun readGraph(buffer: BufferedReader, notOriented: Boolean = false): Edges {
- val (vertexCount, edgeCount) = buffer.readLine().split(" ").map { it.toInt() }
- val edgesLocal = List(vertexCount) { it + 1 }.associateWith { mutableListOf<Int>() }
- repeat(edgeCount) {
- val (vertex, toVertex) = buffer.readLine().split(" ").map { it.toInt() }
- edgesLocal[vertex]!!.add(toVertex)
- if (notOriented)
- edgesLocal[toVertex]!!.add(vertex)
- }
- return edgesLocal
- }
- enum class Color {
- WHITE,
- GREY,
- BLACK
- }
- fun Edges.bfs(v: Int, u: Int): String {
- val colors = Array(size + 1) { Color.WHITE }
- val distance = IntArray(size + 1) { -1 }
- val queue = LinkedList<Int>()
- queue.push(v)
- distance[v] = 0
- colors[v] = Color.GREY
- while (queue.any() && distance[u] < 0) {
- val cur = queue.poll()
- this[cur]!!.forEach {
- if (colors[it] == Color.WHITE) {
- distance[it] = distance[cur] + 1
- queue.add(it)
- colors[it] = Color.GREY
- }
- }
- colors[cur] = Color.BLACK
- }
- return distance[u].toString()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement