• + 0 comments

    My Javascript solution that passes all test cases with explanations:

    function bfs(n, m, edges, s) {
        let graph = {}
        // fill the graph with empty sets (equivalent to Python's defaultdict(set))
        Array(n+1).fill(null).forEach((v, i) => graph[i] = new Set())
        
        let result = []
        
        // Construct graph double linked (undirected)
        for (let [n1, n2] of edges) {
            graph[n1].add(n2)
            graph[n2].add(n1)
        }
        
        // For node i = 1...n calculate distance from the start node to 'i'
        for (let i = 1; i <= n; i++) {
            if (i == s) continue // skip start node in the result array
            
            let queue = []
            // We use distances array also as visited array
            let distances = Array(n+1).fill(null).map(_ => -1) // start distance as -1 for all
            distances[s] = 0 // starting node has distance of 0
            queue.push(s)
            
            // BFS LOOP ----------------------------
            while (queue.length > 0) {
                let node = queue.shift()
                for (let neighbor of graph[node]) {
                    if (distances[neighbor] === -1) {
                        queue.push(neighbor)
                        // each distance is 6 more than the previous node
                        distances[neighbor] = distances[node] + 6
                        if (neighbor === i) { // if the target node i is reached
                            queue = [] // set the queue to empty to break the outer loop
                            break // no need to continue inner loop either
                        }
                    }
                }
            }
            result.push(distances[i] || -1)
        }
        return result
    }