-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFindConnectedComponents.m
85 lines (70 loc) · 2.31 KB
/
FindConnectedComponents.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
function [clusters_assignments] = FindConnectedComponents(adjacent_matrix)
%==========================================================================
%
% FindConnectedComponents
% -----------------------
%
% Parameters:
% adjacent_matrix - The adjacent matrix
% N - The Number of samples.
%
% Return Value:
% clusters_assignments - label each point with its
% cluster assignement.
%
% Finds Connected Components in the graph represented by
% the adjacency matrix, each component represents a cluster.
%
%
%==========================================================================
% January 13, 2009
% Implemented by Daewon Lee
% WWW: http://sites.google.com/site/daewonlee/
%==========================================================================
% the clustering vector
N=size(adjacent_matrix,1);
clusters_assignments = zeros(N,1);
cluster_index = 0;
done = 0; % boolean - are we done clustering
while (done ~= 1)
% select an un-clustered root for the DFS
root = 1;
while (clusters_assignments(root) ~= 0)
root = root + 1;
if (root > N) % all nodes are clustered
done = 1;
break;
end
end
% DFS
% ===
if (done ~= 1) % an unclustered node was found - start DFS
% a new cluster was found
cluster_index = cluster_index + 1;
% the DFS stack
stack = zeros(N,1);
stack_index = 0;
% put the root in the stack
stack_index = stack_index + 1;
stack(stack_index) = root;
% as long as the stack in not empty - continue
while (stack_index ~= 0);
% take a node from the stack
node = stack(stack_index);
stack_index = stack_index - 1;
% assign the cluster number to it
clusters_assignments(node) = cluster_index;
% check all its neighbors
for i = [1:N]
% check that this node is a neighbor and not clustered yet
if (adjacent_matrix(node,i) == 1 & ...
clusters_assignments(i) == 0 & ...
i ~= node)
% add to stack
stack_index = stack_index + 1;
stack(stack_index) = i;
end
end
end
end
end