Advertisement
aimon1337

Untitled

Dec 20th, 2022
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1.  
  2. struct comparator
  3. {
  4. bool operator()(const std::pair<int, Node>& pair1, const std::pair<int, Node>& pair2)
  5. {
  6. return pair1.first < pair2.first;
  7. }
  8. };
  9.  
  10. void Graph::Dijkstra(Node start, Node end)
  11. {
  12. if (!exitPath.empty()) exitPath.clear();
  13. std::vector<bool> vis(m_nodes.size(), false);
  14. std::vector<int> dist(m_nodes.size(), 0x3f3f3f3f);
  15. std::priority_queue < std::pair<int, Node>, std::deque<std::pair<int, Node>>, comparator> pq;
  16. for (const auto& node : m_nodes)
  17. {
  18. if (node == start) continue;
  19. vis[node.GetInfo()] = false;
  20. }
  21. vis[start.GetInfo()] = false;
  22. dist[start.GetInfo()] = 0;
  23. pq.push({dist[start.GetInfo()], start});
  24. finished = false;
  25. Node curr;
  26. while (!pq.empty())
  27. {
  28. do
  29. {
  30. curr = pq.top().second;
  31. pq.pop();
  32. } while (vis[curr.GetInfo()] == true);
  33. vis[curr.GetInfo()] = true;
  34. if (curr == end)
  35. {
  36. finished = true;
  37. break;
  38. }
  39. auto vec = GetConnectionsOfCurrNode(curr);
  40. for (const auto& it : vec)
  41. {
  42. if (vis[it.GetSecondNode().GetInfo()] == false)
  43. {
  44. Node next = it.GetSecondNode();
  45. int cost = it.GetCost();
  46. if (dist[next.GetInfo()] > dist[curr.GetInfo()] + cost)
  47. {
  48. dist[next.GetInfo()] = dist[curr.GetInfo()] + cost;
  49. exitPath.emplace_back(it);
  50. pq.push({dist[next.GetInfo()], next});
  51. }
  52. }
  53. }
  54. }
  55. if (finished)
  56. {
  57. qDebug() << "Am gasit pathul cel mai scurt";
  58. }
  59. else
  60. {
  61. qDebug() << "N-am gasit...";
  62. }
  63. }
  64.  
  65. std::vector<Edge> Graph::GetConnectionsOfCurrNode(const Node& node)
  66. {
  67. std::vector<Edge> ans;
  68. for (const auto& edge : m_edges)
  69. {
  70. if (edge.GetFirstNode() == node)
  71. {
  72. ans.emplace_back(edge);
  73. }
  74. }
  75. return ans;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement