Untitled
🧩 Syntax:
import java.io.*;
import java.util.*;
// To execute Kotlin code, please define a top level function named main
fun main() {
val matrix = Array(5) { IntArray(5) { 0 } }
matrix[0][1] = 1
matrix[1][2] = 1
matrix[1][4] = 1
matrix[3][2] = 1
matrix[4][3] = 1
(0..4).forEach { id ->
println("id=$id, output=${Solution().affectedCells(id, matrix)}")
}
// 0 -> 1 -> 4 -> 3
// |--> 2 <--|
// ex: 0 -> 0, 1, 4, 3, 2
// ex: 1 -> 1, 4, 3, 2
// ex: 2 -> 2
// ex: 3 -> 3, 2
// ex: 4 -> 4, 3, 2
// matrix
// 0 1 2 3 4
// 0 0 1 0 0 0
// 1 0 0 1 0 1
// 2 0 0 0 0 0
// 3 0 0 1 0 0
// 4 0 0 0 1 0
}
data class Cell(val id: Int)
class Solution() {
fun affectedCells(id: Int, matrix: Array<IntArray>): List<Int> {
val dependents = (0 until matrix.size).filter { j ->
matrix[id][j] == 1
}
return (if (dependents.isNotEmpty()) {
val unflattened = dependents
.map { dependent -> affectedCells(dependent, matrix) }
unflattened.flatten()
} else {
listOf()
} + id).distinct()
}
fun print(matrix: Array<IntArray>) {
matrix.forEach { row -> println(row.contentToString()) }
}
}