bfs.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "bfs.h"
  2. #include "list_to_matrix.h"
  3. #include <vector>
  4. #include <queue>
  5. template <
  6. typename AType,
  7. typename DerivedD,
  8. typename DerivedP>
  9. IGL_INLINE void igl::bfs(
  10. const AType & A,
  11. const size_t s,
  12. Eigen::PlainObjectBase<DerivedD> & D,
  13. Eigen::PlainObjectBase<DerivedP> & P)
  14. {
  15. std::vector<typename DerivedD::Scalar> vD;
  16. std::vector<typename DerivedP::Scalar> vP;
  17. bfs(A,s,vD,vP);
  18. list_to_matrix(vD,D);
  19. list_to_matrix(vP,P);
  20. }
  21. template <
  22. typename AType,
  23. typename DType,
  24. typename PType>
  25. IGL_INLINE void igl::bfs(
  26. const std::vector<std::vector<AType> > & A,
  27. const size_t s,
  28. std::vector<DType> & D,
  29. std::vector<PType> & P)
  30. {
  31. // number of nodes
  32. int N = s+1;
  33. for(const auto & Ai : A) for(const auto & a : Ai) N = std::max(N,a+1);
  34. std::vector<bool> seen(N,false);
  35. P.resize(N,-1);
  36. std::queue<std::pair<int,int> > Q;
  37. Q.push({s,-1});
  38. while(!Q.empty())
  39. {
  40. const int f = Q.front().first;
  41. const int p = Q.front().second;
  42. Q.pop();
  43. if(seen[f])
  44. {
  45. continue;
  46. }
  47. D.push_back(f);
  48. P[f] = p;
  49. seen[f] = true;
  50. for(const auto & n : A[f]) Q.push({n,f});
  51. }
  52. }
  53. template <
  54. typename AType,
  55. typename DType,
  56. typename PType>
  57. IGL_INLINE void igl::bfs(
  58. const Eigen::SparseMatrix<AType> & A,
  59. const size_t s,
  60. std::vector<DType> & D,
  61. std::vector<PType> & P)
  62. {
  63. // number of nodes
  64. int N = A.rows();
  65. assert(A.rows() == A.cols());
  66. std::vector<bool> seen(N,false);
  67. P.resize(N,-1);
  68. std::queue<std::pair<int,int> > Q;
  69. Q.push({s,-1});
  70. while(!Q.empty())
  71. {
  72. const int f = Q.front().first;
  73. const int p = Q.front().second;
  74. Q.pop();
  75. if(seen[f])
  76. {
  77. continue;
  78. }
  79. D.push_back(f);
  80. P[f] = p;
  81. seen[f] = true;
  82. for(typename Eigen::SparseMatrix<AType>::InnerIterator it (A,f); it; ++it)
  83. {
  84. if(it.value()) Q.push({it.index(),f});
  85. }
  86. }
  87. }