Skip to content

Instantly share code, notes, and snippets.

@b00blik
Last active February 11, 2020 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b00blik/e91bb3285b8137436cd2c19225ef0886 to your computer and use it in GitHub Desktop.
Save b00blik/e91bb3285b8137436cd2c19225ef0886 to your computer and use it in GitHub Desktop.
Exploring graphs
import java.util.*;
class Graph {
int V; //num. of Vertices
LinkedList<Integer> adj[]; //Adjacency lists
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0 ; i<v; i++) {
adj[i] = new LinkedList<>();
}
}
void addEdge(int v, int w) {
adj[v].add(w);
}
void BFS(int s) {
//Mark all vertices as unvisited (by default elements in array are false)
boolean visited[] = new boolean[V];
//Queue creating
LinkedList<Integer> queue = new LinkedList<>();
//marked current vertex as visited
visited[s] = true;
//enqueue this vertex
queue.add(s);
while (queue.size() != 0) {
System.out.println("\n\nBefore dequeue: " + Arrays.toString(queue.toArray()));
//dequeue vertex
s = queue.poll();
System.out.println("Getting from queue: " + s);
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
Iterator<Integer> i = adj[s].listIterator();
while(i.hasNext()) {
int n = i.next();
if (!visited[n]) {
System.out.println("Visited: " + s + " -> " + n);
visited[n] = true;
queue.add(n);
}
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(10);
graph.addEdge(0,1);
graph.addEdge(0,2);
graph.addEdge(0,3);
graph.addEdge(1,4);
graph.addEdge(2,5);
graph.addEdge(2,6);
graph.addEdge(3,7);
graph.addEdge(4,8);
graph.addEdge(5,9);
System.out.println("Starting BFS from vertex 0");
graph.BFS(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment