All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2301_2400.s2368_reachable_nodes_with_restrictions.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.30
Show newest version
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
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy