📍 C++ Solution with Pattern for future Questions
\uD83D\uDD25 Please Upvote It is FREE from your side\n\nWhere this Approach can be used [Pattern]\n- Whenever we want to find max or min cost path from a source
\uD83D\uDD25 Please **Upvote** It is **FREE** from your side\n\n**Where this Approach can be used** [Pattern]\n- Whenever we want to find max or min cost path from a source to destination. \n- It will also work if the nodes are disconnected means more than one graph present which are not connected with each other\n- We can use this algorithm in both directed and undirected graph.\n\n**Approach:-** We can use **Dijkastra here alongwith prioirty_queue** which ensures that a node will always visit its neighbours with minimum distance possible. Maintain a distance vector which is time in this case. **One mistake that I was doing** is in the if condition ```time[node] + x.second < time[x.first] && !visited[x.first]``` I was not putting visited and was using <= inequality. It will make us looping infinitely incase graph has a cycle and equal cost of reaching the nodes.\n\nDry run a case you\'ll understand.\n\n```\n#define pii pair<int, int>\nclass Solution {\npublic:\n    int networkDelayTime(vector<vector<int>>& times, int n, int k) {\n        vector<vector<pair<int, int>>> adj(n+1); // (node, time)\n        for(int i = 0; i<times.size(); i++){\n            adj[times[i][0]].push_back({times[i][1], times[i][2]});\n        }\n        vector<int> visited(n+1,0);\n        vector<int> time(n+1,INT_MAX);\n        time[k] = 0;\n        priority_queue<pii, vector<pii>,greater<pii>> nodes;\n        nodes.push({0,k});\n        while(!nodes.empty()){\n            int node = nodes.top().second;\n            nodes.pop();\n            visited[node] = 1;\n            for(auto &x: adj[node]){\n                if(time[node] + x.second < time[x.first] && !visited[x.first]){\n                    time[x.first] = min(time[node]+x.second, time[x.first]);\n                    nodes.push({time[x.first], x.first});\n                }\n            }\n        }\n        for(int i = 1; i<=n; i++){\n            if(visited[i]==0){\n                return -1;\n            }\n        }\n        int timeToReach = time[1];\n        for(int i = 1; i<=n; i++){\n            // cout<<time[i]<<\' \';\n            timeToReach = max(timeToReach, time[i]);\n        }\n        return timeToReach;\n    }\n};\n```
['C', 'C++']