How do you calculate the number of connected charts?

Given a node array and an array of edges, how do you calculate the number of connected graphs?

+3
source share
5 answers
  • Start from one of the nodes to make BFS or DFS to get all the nodes connected from this node.
  • Now go to the node list to find any node that is no longer included,
  • follow the same procedure on node. Repeat until all sites are visited.
  • Now you will have all the graphs in your data.
+1
source

( ). , , . , , , .

+1

, :

make_set (v) , v.

(x, y) x y.

get_representatve (v) , node .

G = (V, E):

foreach vertex v in V:
    make_set(v)

foreach edge (u, v) in E:
    if get_representatve(u) != get_representatve:
         union(u, v)

- ;-) , , Tarjan.

, .

+1

, , , O (| V | + | E |).

visited := the empty set
count := 0
for each vertex v in vertices:
    if v not in visited:
        count++
        add v and all nodes reachable from v to visited
return count
0

O (n) DFS. :

explore , , node. , DFS, node node .

, DFS node explore node. ( cc) explore , . , hashmap/dictionary , cc node. explore node cc . , , cc.

Each time it explorereturns to the DFS cycle, increment ccand pass this value the next time. After you finish with all of DFS, you will have a dictionary that maps to each node the corresponding number of the connected component. The value ccat the end of this procedure can give you the number of connected components that are on the graph.

Here's the pseudo code:

function explore(node, graph, cc, map){
    map(currentNode) = cc
    //find all children of current node, and push onto stack. 
    //mark current node as visited
    for i in stack:
        explore(i, graph, cc, map)
}

function DFS{
     int cc = -1
     for node in keysOfGraph:
          if not visited:
              cc++
              explore(node, graph, cc, map)

return cc
}

From Dasgupt Algorithms (section 3.2.3)

0
source

Source: https://habr.com/ru/post/1796432/


All Articles