Search code examples
graphgraph-theoryconnected-components

Split undirected graph by negative edges


Wondering if there exists an algorithm to split an undirected connected component graph given negative edges.

Essentially the vertices provided in negative edges should be unreachable.


Solution

  • If you want the connected components of your graph that contains only positive edges, then first delete all negative edges from your graph. Then run a DFS (depth-first-search) to find all connected components.

    Here is the algorithm.

    Begin 
        For each edge e in graph G, if e is negative, remove e from G.
    
        For each vertex v in G, do:
            If v is not labeled as visited
                Let c be a new component, and add c to set C.
                Call procedure DFS(v, c) to find one component of positive edges only.
            End If
        End For
    
        The set C contains all the connected components consisting of positive edges only.
    End
    
    Procedure DFS(v, c)
        Add v to c, and label v as visited.
        For each edge from v to w, do
            If vertex w is not labeled as visited then
                Call DFS(G,w)
            End If
        End For
    End Procedure