dijkstra.cpp 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <igl/dijkstra.h>
  2. template <typename IndexType, typename DerivedD, typename DerivedP>
  3. IGL_INLINE int igl::dijkstra_compute_paths(const IndexType &source,
  4. const std::set<IndexType> &targets,
  5. const std::vector<std::vector<IndexType> >& VV,
  6. Eigen::PlainObjectBase<DerivedD> &min_distance,
  7. Eigen::PlainObjectBase<DerivedP> &previous)
  8. {
  9. int numV = VV.size();
  10. min_distance.setConstant(numV, 1, std::numeric_limits<typename DerivedD::Scalar>::infinity());
  11. min_distance[source] = 0;
  12. previous.setConstant(numV, 1, -1);
  13. std::set<std::pair<typename DerivedD::Scalar, IndexType> > vertex_queue;
  14. vertex_queue.insert(std::make_pair(min_distance[source], source));
  15. while (!vertex_queue.empty())
  16. {
  17. typename DerivedD::Scalar dist = vertex_queue.begin()->first;
  18. IndexType u = vertex_queue.begin()->second;
  19. vertex_queue.erase(vertex_queue.begin());
  20. if (targets.find(u)!= targets.end())
  21. return u;
  22. // Visit each edge exiting u
  23. const std::vector<int> &neighbors = VV[u];
  24. for (std::vector<int>::const_iterator neighbor_iter = neighbors.begin();
  25. neighbor_iter != neighbors.end();
  26. neighbor_iter++)
  27. {
  28. IndexType v = *neighbor_iter;
  29. typename DerivedD::Scalar distance_through_u = dist + 1.;
  30. if (distance_through_u < min_distance[v]) {
  31. vertex_queue.erase(std::make_pair(min_distance[v], v));
  32. min_distance[v] = distance_through_u;
  33. previous[v] = u;
  34. vertex_queue.insert(std::make_pair(min_distance[v], v));
  35. }
  36. }
  37. }
  38. //we should never get here
  39. return -1;
  40. }
  41. template <typename IndexType, typename DerivedP>
  42. IGL_INLINE void igl::dijkstra_get_shortest_path_to(const IndexType &vertex,
  43. const Eigen::PlainObjectBase<DerivedP> &previous,
  44. std::vector<IndexType> &path)
  45. {
  46. IndexType source = vertex;
  47. path.clear();
  48. for ( ; source != -1; source = previous[source])
  49. path.push_back(source);
  50. }
  51. #ifdef IGL_STATIC_LIBRARY
  52. // Explicit template specialization
  53. template int igl::dijkstra_compute_paths<int, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(int const&, std::set<int, std::less<int>, std::allocator<int> > const&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
  54. template void igl::dijkstra_get_shortest_path_to<int, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(int const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, std::vector<int, std::allocator<int> >&);
  55. #endif