Find a vertex that all other vertices can be reached from in a digraph

前端 未结 4 974
傲寒
傲寒 2021-02-15 18:03

Given a directed graph, how can we determine whether or not there exists a vertex v, from which all other vertices are reachable. the algorithm should be as efficient as possibl

4条回答
  •  被撕碎了的回忆
    2021-02-15 18:40

    import java.util.*;
    
    public class FindMotherVertex {
        public static void main(String[] arg) {
            List edges = Arrays.asList(
                new Edges(0, 1), new Edges(0, 2),
                new Edges(1, 3),
                new Edges(4, 1),
                new Edges(5, 2), new Edges(5, 6),
                new Edges(6, 4),
                new Edges(6, 0)
            );
            findMotherVertex(graph);
    
        }
        public static void findMotherVertex(Graph graph) {
            int motherVertex =  0;
            boolean[] visited = new boolean[7];
    
            for (int i=0;i<7;i++) {  
                if (visited[i] == false) {  //marked - boolean array storing visited vertices
                    DFS(graph,i,visited);
                    motherVertex= i;
                }
    
            }
    
            //Check for this vertex if all other vertices have been already visited
            //Otherwise no mother vertex exists
    
            for (int i=0;i<6;i++) {
                if (!visited[i]){ visited[i] = false;}
    
            }
    
            System.out.println("Mother vertex is : " + motherVertex);
        }
    
        public static void DFS(Graph graph, int v,boolean[] visited) {
    
            //create a stack used to do DFS
            Stack stack = new Stack<>();
            stack.add(v);
            //Run While queue is empty
    
            while (!stack.isEmpty()) {
                //Pop vertex from stack
                v = stack.pop();
    
                if (visited[v])
                    continue;
                visited[v] = true;
                System.out.print("(" + v + ")" + "===>");
    // do for every edge
                List list = graph.adj.get(v);
                for (int i = list.size() - 1; i >= 0; i--) {
                    int u = list.get(i);
                    if (!visited[u]) ;
                    stack.push(u);
                }
            }
    
        }
    
    
        static class Graph {
    
            //List of List to represent Adajacency List
            List> adj = new ArrayList<>();
            //Constructor to construct Graph
    
            public Graph(List edges) {
                //Allocate memory for adjacency List
                for (int i = 0; i < edges.size(); i++) {
                    adj.add(i, new ArrayList<>());
                }
    
                //Add edges to the undirected Graph
                for (Edges curr : edges) {
                    adj.get(curr.src).add(curr.desc);
    
    
                }
    
            }
    
        }
    }
    

提交回复
热议问题