Breadth first search (BFS) java program | Using adjacency list


import java.util.List;
import java.util.ArrayList;
import java.util.Queue;
import java.util.ArrayDeque;

class BreadthFirstPaths {
    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[] distTo; // distance from s to v
    private int s;
    
    public BreadthFirstPaths(Graph G, int s) {
        // initialize data structures
        this.visited = new boolean[G.V()];
        this.edgeTo = new int[G.V()];
        this.distTo = new int[G.V()];
        this.s = s;
        
        // find vertices connected to s
        bfs(G, s);
    }
    
    private void bfs(Graph G, int s) {
        int distance = 0;
        Queue q = new ArrayDeque();
        System.out.print(s + "->");
        visited[s] = true;
        q.offer(s);
        distTo[s] = distance;
        while(!q.isEmpty()) {
            distance++;
            int v = q.poll();
            for(int w : G.adj(v)) {
                if(!visited[w]) {
                    System.out.print(w + "->");
                    visited[w] = true;
                    q.offer(w);
                    edgeTo[w] = v;
                    distTo[w] = distance;
                }
            }
        }
    }
    
    private static Graph prepareGraph() {
        int[][] edges = new int[][] {
		    {0, 5},
		    {2, 4},
		    {2, 3},
		    {1, 2},
		    {0, 1},
		    {3, 4},
		    {3, 5},
		    {0, 2}
		};
		
		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: ");
		BreadthFirstPaths breadthFirstPaths = new BreadthFirstPaths(G, s);
	}
}


Preparing graph 
V: 8
E: 8
All connected vertices to 0 are: 
0->5->1->2->3->4->

Comments

Popular posts from this blog

gsutil Vs Storage Transfer Service Vs Transfer Appliance

SQL basic interview question