Advertisement
Singasking

Untitled

Jun 28th, 2023
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/
  2.  
  3. class Solution {
  4. public:
  5. void dfs(vector<vector<pair<int,int>>> &adj,int node, vector<int>& visit,int& count,int& tTime, int cTime,int finalNode) {
  6.  
  7. visit[node]=1;
  8.  
  9. for(int i=0;i<adj[node].size();i++) {
  10. pair<int,int> x = adj[node][i];
  11. int n = x.first;
  12. int etime = x.second;
  13. if(n==finalNode && cTime+etime==tTime) {
  14. count+=1;
  15. continue;
  16. }
  17. if(visit[n]==0) {
  18. dfs(adj,n,visit,count,tTime,cTime+etime,finalNode);
  19. }
  20. }
  21.  
  22. visit[node]=0;
  23.  
  24. }
  25. int countPaths(int n, vector<vector<int>>& roads) {
  26. vector<vector<pair<int,int>>> adj(n);
  27. for (auto road:roads) {
  28. adj[road[0]].push_back({road[1],road[2]});
  29. adj[road[1]].push_back({road[0],road[2]});
  30. }
  31.  
  32. int mod = 1e9+7;
  33.  
  34. priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
  35. vector<int> time(n,1e7);
  36. pq.push({0,0});
  37.  
  38.  
  39. while(!pq.empty()) {
  40. //Pop the node
  41. auto temp = pq.top();
  42. pq.pop();
  43. int t(temp.first),node(temp.second);
  44.  
  45. for(auto x:adj[node]){
  46. //Find the neighbour & visit it
  47. int xxx = x.first;
  48. // return xxx;
  49. int ttt = x.second;
  50.  
  51. if(ttt+t<time[xxx]) {
  52.  
  53. time[xxx] = ttt+t;
  54. if(xxx==n-1) break;
  55. pq.push({time[xxx],xxx});
  56. }
  57. }
  58. }
  59.  
  60. int minTime = time[n-1];
  61.  
  62. vector<int> visit(n,0);
  63.  
  64. int count=0;
  65. dfs(adj,0,visit,count,minTime,0,n-1);
  66. return count;
  67. }
  68. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement