Skip to content

Commit 5812c93

Browse files
committed
using lambda for dfs
1 parent a2c3e74 commit 5812c93

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

src/conncomp.h

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <Eigen/Core>
2323
#include <Eigen/SparseCore>
2424

25+
#include <functional>
2526

2627
//! Sparse incidence matrix and connected components
2728
namespace Graph {
@@ -35,10 +36,37 @@ using Eigen::Vector;
3536

3637

3738
//! Matlab's bins = conncomp( AA, 'outputForm', 'vector')
38-
[[nodiscard,maybe_unused]] static VectorXi conncomp(const SparseMatrix<int, ColMajor> &AA)
39+
[[nodiscard,maybe_unused]] static VectorXi
40+
conncomp(const SparseMatrix<int, ColMajor> &AA)
3941
{
4042

41-
static VectorXi m_comp; // index vector components, 0-based
43+
VectorXi component; // index vector components, 0-based
44+
Vector<bool,Dynamic> visited; // for each vertex: visited?
45+
46+
const Index V = AA.rows(); // number of vertices
47+
48+
visited.setConstant( V,false);
49+
component.setConstant( V,-1);
50+
int num_connected_components = 0;
51+
52+
std::function<void(Index,Index)> dfs = [&](const int c, const Index v){
53+
visited(v) = true;
54+
component(v) = c;
55+
for ( SparseMatrix<int,ColMajor>::InnerIterator it(AA,v); it; ++it) {
56+
if ( !visited(it.index()) ) {
57+
dfs( c, it.row() );
58+
}
59+
}
60+
};
61+
62+
for ( Index v=0; v<V; v++ ) {
63+
if ( !visited(v) ) {
64+
dfs( num_connected_components++, v );
65+
}
66+
}
67+
return component;
68+
69+
/*static VectorXi m_comp; // index vector components, 0-based
4270
static Vector<bool,Dynamic> m_visited; // for each vertex: visited?
4371
4472
struct s {
@@ -66,7 +94,7 @@ using Eigen::Vector;
6694
}
6795
}
6896
69-
return m_comp;
97+
return m_comp;*/
7098
}
7199

72100

0 commit comments

Comments
 (0)