Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def generateGraph(z):
- '''
- Generates a dictionary {vertex: set(links)} from the matrix
- '''
- graph = {}
- for key,value in enumerate(range(0,len(z))):
- z[value] = list(z[value])
- graph[value] = set()
- for k,v in enumerate(z[value]):
- if int(z[value][k]) == 1:
- graph[value].add(k)
- return graph
- def countClusters(graph):
- '''
- Counts the number of independent sub-graphs
- '''
- clusters = 0
- while graph != {}:
- clusters += 1
- for edge in graph[next(iter(graph))]:
- if edge in graph:
- for vertex in depthFirstSearch(graph,edge):
- del graph[vertex]
- return clusters
- def depthFirstSearch(graph, vertex, visited=None):
- '''
- Searches a graph by vising recursively all vertices
- '''
- if visited is None:
- visited = set()
- visited.add(vertex)
- for nextVertex in graph[vertex] - visited:
- dfs(graph, nextVertex, visited)
- return visited
- m = ['11000',
- '11000',
- '00110',
- '00110',
- '00001']
- graph = generateGraph(m)
- clusters = countClusters(graph)
- print clusters
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement