g2301_2400.s2368_reachable_nodes_with_restrictions.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g2301_2400.s2368_reachable_nodes_with_restrictions
// #Medium #Array #Hash_Table #Depth_First_Search #Breadth_First_Search #Tree #Graph
// #2023_07_02_Time_1199_ms_(76.92%)_Space_111.6_MB_(100.00%)
import java.util.ArrayDeque
import java.util.Queue
class Solution {
fun reachableNodes(n: Int, edges: Array, restricted: IntArray): Int {
val graph: Array?> = arrayOfNulls(n)
for (i in 0 until n) {
graph[i] = ArrayList()
}
for (edge in edges) {
val src = edge[0]
val dest = edge[1]
graph[src]?.add(dest)
graph[dest]?.add(src)
}
val q: Queue = ArrayDeque()
val visited = BooleanArray(n)
q.offer(0)
visited[0] = true
for (node in restricted) {
visited[node] = true
}
var ans = 0
while (q.isNotEmpty()) {
val vertex = q.poll()
ans++
for (neighbour in graph[vertex]!!) {
if (!visited[neighbour]) {
q.offer(neighbour)
visited[neighbour] = true
}
}
}
return ans
}
}