Simple Solution with Diagrams in Video - JavaScript, C++, Java, Python
Video\nPlease upvote here so others save time too!\n\nLike the video on YouTube if you found it useful\n\nClick here to subscribe on YouTube:\nhttps://www.youtu
# Video\nPlease upvote here so others save time too!\n\nLike the video on YouTube if you found it useful\n\nClick here to subscribe on YouTube:\nhttps://www.youtube.com/@mayowadan?sub_confirmation=1\n\nThanks!\n\nhttps://youtu.be/mJT48XM9g9g?si=l_zKDD8aCgzvo5vi\n\n```Javascript []\n/**\n * @param {number[][]} times\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar networkDelayTime = function (times, n, k) {\n    const adjacency = new Map();\n    for (const time of times) {\n        const src = time[0];\n        const dst = time[1];\n        const t = time[2];\n        if (!adjacency.has(src)) {\n            adjacency.set(src, []);\n        }\n        adjacency.get(src).push([dst, t]);\n    }\n\n    const pq = [];\n    pq.push({ node: k, time: 0 });\n    const visited = new Set();\n    let delays = 0;\n\n    while (pq.length > 0) {\n        pq.sort((a, b) => a.time - b.time);\n        const { time, node } = pq.shift();\n\n        if (visited.has(node)) {\n            continue;\n        }\n\n        visited.add(node);\n        delays = Math.max(delays, time);\n        const neighbors = adjacency.get(node) || []; // Handle case when there are no neighbors\n\n        for (const neighbor of neighbors) {\n            const neighborNode = neighbor[0];\n            const neighborTime = neighbor[1];\n            if (!visited.has(neighborNode)) {\n                const newTime = time + neighborTime;\n                pq.push({ node: neighborNode, time: newTime });\n            }\n        }\n    }\n\n    if (visited.size === n) {\n        return delays;\n    }\n\n    return -1;\n};\n```\n```Python []\nclass Solution:\n    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n        # Create adjacency list\n        adjacency = {i: [] for i in range(1, n + 1)}\n        for src, dst, time in times:\n            adjacency[src].append((dst, time))\n\n        # Priority queue for Dijkstra\'s algorithm (min-heap based on time)\n        pq = [(0, k)]  # (time, node)\n        visited = set()\n        delays = 0\n\n        while pq:\n            time, node = heapq.heappop(pq)\n\n            # Skip if the node has been visited\n            if node in visited:\n                continue\n\n            visited.add(node)\n            delays = max(delays, time)\n\n            for neighbor, neighbor_time in adjacency.get(node, []):\n                if neighbor not in visited:\n                    heapq.heappush(pq, (time + neighbor_time, neighbor))\n\n        # Check if all nodes have been visited\n        return delays if len(visited) == n else -1\n\n```\n```Java []\nclass Solution {\n    public int networkDelayTime(int[][] times, int n, int k) {\n        // Create adjacency list\n        Map<Integer, List<int[]>> adjacency = new HashMap<>();\n        for (int[] time : times) {\n            int src = time[0];\n            int dst = time[1];\n            int t = time[2];\n            adjacency.computeIfAbsent(src, key -> new ArrayList<>()).add(new int[] { dst, t });\n        }\n\n        // Priority queue for Dijkstra\'s algorithm (min-heap based on time)\n        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));\n        pq.add(new int[] { k, 0 });\n        Set<Integer> visited = new HashSet<>();\n        int delays = 0;\n\n        while (!pq.isEmpty()) {\n            int[] current = pq.poll();\n            int time = current[1];\n            int node = current[0];\n\n            // Skip if the node has been visited\n            if (!visited.add(node)) {\n                continue;\n            }\n\n            delays = Math.max(delays, time);\n            List<int[]> neighbors = adjacency.getOrDefault(node, new ArrayList<>());\n\n            for (int[] neighbor : neighbors) {\n                int neighborNode = neighbor[0];\n                int neighborTime = neighbor[1];\n                if (!visited.contains(neighborNode)) {\n                    pq.add(new int[] { neighborNode, time + neighborTime });\n                }\n            }\n        }\n\n        // Check if all nodes have been visited\n        return visited.size() == n ? delays : -1;\n    }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n    int networkDelayTime(vector<vector<int>>& times, int n, int k) {\n        // Create adjacency list\n        unordered_map<int, vector<pair<int, int>>> adjacency;\n        for (const auto& time : times) {\n            int src = time[0];\n            int dst = time[1];\n            int t = time[2];\n            adjacency[src].emplace_back(dst, t);\n        }\n\n        // Priority queue for Dijkstra\'s algorithm (min-heap based on time)\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;\n        pq.emplace(0, k);\n        set<int> visited;\n        int delays = 0;\n\n        while (!pq.empty()) {\n            auto [time, node] = pq.top();\n            pq.pop();\n\n            // Skip if the node has been visited\n            if (visited.count(node)) {\n                continue;\n            }\n\n            visited.insert(node);\n            delays = max(delays, time);\n            for (const auto& neighbor : adjacency[node]) {\n                int neighborNode = neighbor.first;\n                int neighborTime = neighbor.second;\n                if (!visited.count(neighborNode)) {\n                    pq.emplace(time + neighborTime, neighborNode);\n                }\n            }\n        }\n\n        // Check if all nodes have been visited\n        return visited.size() == n ? delays : -1;\n    }\n};\n\n```
['Python', 'C++', 'Java', 'Python3', 'JavaScript']