Java – find the largest connected component in the adj matrix graph?

I try to find a way to find the largest connected component in adj matrix graph For example:

0000000110
0001100000
0000000000
0100000010
0100000100
0000000100
0000000000
1000110000
1001000000
0000000000

I have asked Google this question and am trying to find anything. I have also read wiki articles on graph theory and am not happy I think they must be an algorithm to solve this problem Anyone can point me in the right direction and give me some instructions. What should I do to solve this problem?

Solution

Choose a starting point and start "walking" to other nodes until you are exhausted Perform this operation before all components are found This will run in O (n), where n is the size of the graph

Framework of Python solution:

class Node(object):
    def __init__(self,index,neighbors):
        self.index = index
        # A set of indices (integers,not Nodes)
        self.neighbors = set(neighbors)

    def add_neighbor(self,neighbor):
        self.neighbors.add(neighbor)


class Component(object):
    def __init__(self,nodes):
        self.nodes = nodes
        self.adjacent_nodes = set()
        for node in nodes:
            self.adjacent_nodes.add(node.index)
            self.adjacent_nodes.update(node.neighbors)

    @property
    def size(self):
        return len(self.nodes)

    @property
    def node_indices(self):
        return set(node.index for node in self.nodes)

    @property
    def is_saturated(self):
        return self.node_indices == self.adjacent_nodes

    def add_node(self,node):
        self.nodes.append(node)
        self.adjacent_nodes.update(node.neighbors)


adj_matrix = [[0,1,0],[0,[1,0]]
matrix_size = len(adj_matrix)

nodes = {}
for index in range(matrix_size):
    neighbors = [neighbor for neighbor,value in enumerate(adj_matrix[index])
                 if value == 1]
    nodes[index] = Node(index,neighbors)

components = []
index,node = nodes.popitem()
component = Component([node])
while nodes:
    if not component.is_saturated:
        missing_node_index = component.adjacent_nodes.difference(component.node_indices).pop()
        missing_node = nodes.pop(missing_node_index)
        component.add_node(missing_node)
    else:
        components.append(component)

        index,node = nodes.popitem()
        component = Component([node])

# Final component needs to be appended as well
components.append(component)

print max([component.size for component in components])
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>