https://coderun.yandex.ru/problem/metro-2/description Легкая

Решение

import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.util.LinkedList
import java.util.Queue

fun main() {
    val reader = BufferedReader(InputStreamReader(System.`in`))
    val writer = BufferedWriter(OutputStreamWriter(System.out))
    
    val n = reader.readLine().trim().toInt()
    val m = reader.readLine().trim().toInt()
    
    val lines = Array(m) { mutableSetOf<Int>() }
    for (i in 0 until m) {
        val parts = reader.readLine().trim().split(" ")
        val p = parts[0].toInt()
        for (j in 1..p) {
            lines[i].add(parts[j].toInt())
        }
    }
    
    val (A, B) = reader.readLine().trim().split(" ").map { it.toInt() }
    
    val startLines = mutableListOf<Int>()
    val destLines = mutableSetOf<Int>()
    for (i in 0 until m) {
        if (A in lines[i]) {
            startLines.add(i)
        }
        if (B in lines[i]) {
            destLines.add(i)
        }
    }
    
    if (startLines.isEmpty() || destLines.isEmpty()) {
        writer.write("-1")
        writer.flush()
        return
    }
    
    for (line in startLines) {
        if (line in destLines) {
            writer.write("0")
            writer.flush()
            return
        }
    }
    
    val graph = Array(m) { mutableListOf<Int>() }
    for (i in 0 until m) {
        for (j in i + 1 until m) {
            if (lines[i].any { it in lines[j] }) {
                graph[i].add(j)
                graph[j].add(i)
            }
        }
    }
    
    val distances = IntArray(m) { -1 }
    val queue: Queue<Int> = LinkedList()
    for (line in startLines) {
        distances[line] = 0
        queue.add(line)
    }
    
    var answer = -1
    while (queue.isNotEmpty()) {
        val curLine = queue.poll()
        val curDist = distances[curLine]
        if (curLine in destLines) {
            answer = curDist
            break
        }
        for (nextLine in graph[curLine]) {
            if (distances[nextLine] == -1) {
                distances[nextLine] = curDist + 1
                queue.add(nextLine)
            }
        }
    }
    
    writer.write(answer.toString())
    writer.flush()
    writer.close()
    reader.close()
}