Depth first search (DFS) java program | Using adjacency list | Undirected graph


import java.util.List;
import java.util.ArrayList;
import java.util.Stack;

class DepthFirstPaths {
    private boolean[] visited; // visited[v] = true if v connected to s
    private int[] edgeTo; // edgeTo[v] = previous vertex on path from s to v
    private int s;
    
    public DepthFirstPaths(Graph G, int s) {
        // initialize data structures
        this.visited = new boolean[G.V()];
        this.edgeTo = new int[G.V()];
        this.s = s;
        
        // find vertices connected to s
        dfs(G, s);
    }
    
    // is there a path from s to v?
    public boolean hasPathTo(int v) {
        return visited[v];
    }
    
    // path from s to v; null if no such path
    public Iterable pathTo(int v) {
        if (!hasPathTo(v)) {
            return null;
        }
        Stack path = new Stack();
        int previousVertices = v;
        while(previousVertices != this.s) {
            path.push(previousVertices);
            previousVertices = edgeTo[previousVertices];
        }
        path.push(s);
        return path;
    }
    
    private void dfs(Graph G, int v) {
        // recursive DFS does the work
        System.out.print(v + "->");
        visited[v] = true;
        for (int w : G.adj(v))
        if(!visited[w]) {
            dfs(G, w);
            edgeTo[w] = v;
        }
    }
    
    private static Graph prepareGraph() {
        int[][] edges = new int[][] {
		    {0, 5},
		    {4, 3},
		    {0, 1},
		    {9, 12},
		    {6, 4},
		    {5, 4},
		    {0, 2},
		    {11, 12},
		    {9, 10},
		    {0, 6},
		    {7, 8},
		    {9, 11},
		    {5, 3}
		};
		
		Graph G = new Graph(edges.length);
		// add all edges 
		for(int i = 0; i < edges.length; i++) {
		    int v = edges[i][0];
		    int w = edges[i][1];
		    G.addEdge(v, w);
		}
		return G;
    }
    
    static class Graph {
        private final int V; // number of vertices
        private final List[] adj; // adjacency lists... 0 to V-1
        
        /** create an empty graph with V vertices */
        public Graph(int V) {
            this.V = V;
            this.adj = new ArrayList[V]; // create empty graph with V vertices
            for(int i = 0; i < V; i++) {
                adj[i] = new ArrayList<>();
            }
        }
        
        /** add an edge v-w */
        public void addEdge(int v, int w) {
            // add edge v-w (parallel edges and self-loops allowed)
            adj[v].add(w);
            adj[w].add(v);
        }
        
        /** vertices adjacent to v */
        public Iterable adj(int v) {
            return adj[v];
        }
        
        /** number of vertices */
        public int V() {
            return V;
        }
        
        /** number of edges */
        public int E() {
            int countEdges = 0;
            for(int v = 0; v < V; v++) {
                countEdges += adj[v].size();
            }
            return countEdges/2; // Each edge counted twice
        }
        
        /** string representation */
        public String toString() {
            return "TODO";
        }
    }
    
    public static void main (String[] args) {
	    System.out.println("Preparing graph ");
		Graph G = prepareGraph();
		System.out.println("V: " + G.V());
		System.out.println("E: " + G.E());
		int s = 0;
		System.out.println("All connected vertices to " + s + " are: ");
		DepthFirstPaths depthFirstPaths = new DepthFirstPaths(G, s);
		System.out.println("\nPath to 6 is: ");
		for(Integer i : depthFirstPaths.pathTo(6)) {
		    System.out.print(i + "->");
		}
		
		s = 7;
		System.out.println("\nAll connected vertices to " + s + " are: ");
		new DepthFirstPaths(G, s);
		
		s = 9;
		System.out.println("\nAll connected vertices to " + s + " are: ");
		new DepthFirstPaths(G, s);
	}
}


Preparing graph 
V: 13
E: 13
All connected vertices to 0 are: 
0->5->4->3->6->1->2->
Path to 6 is: 
6->4->5->0->
All connected vertices to 7 are: 
7->8->
All connected vertices to 9 are: 
9->12->11->10->

Comments

Popular posts from this blog

gsutil Vs Storage Transfer Service Vs Transfer Appliance

SQL basic interview question