Simple 15 line JavaScript Solution


  • 1
    F
    function findCircleNum (M) {
        let numCircles = 0
        const visited = new Set ()
        M.forEach ((row, i) => {
            if (visited.has(i)) return
            numCircles++
            const queue = row.map((x, i) => x ? i : -1) . filter ((x) => x > -1)
            while (queue.length > 0) {
                const f = queue.pop ()
                if (!visited.has(f)) {
                    visited.add (f)
                    queue.push(... M[f].map((x, i) => x ? i : -1) . filter ((x) => x > -1))
                }
            }
        })
        return numCircles
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.