Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again.To avoid processing a node more than once, we use a boolean visited array.
For simplicity, it is assumed that all vertices are reachable from the starting vertex (source vertex, in this case 2).
For example, in the following graph, we start the traversal from Vertex-2. When we come to Vertex-0, we look for all adjacent vertices of Vertex-0. Vertex-2 is also an adjacent of Vertex-0. If we don’t mark visited vertices, then Vertex-2 will get processed again and it will become a non-terminating process.
A Breadth First Traversal of the following graph should be 2, 0, 1, 4, 3.
class Graph
{
private int V; // No. of vertices
private LinkedList adj[]; //Adjacency Lists
// Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i queue = new LinkedList();
// Mark the current node as visited and enqueue it
visited[s]=true;
queue.add(s);
while (queue.size() != 0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print(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 i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
// Driver method to
public static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Breadth First Traversal "+
"(starting from vertex 2)");
g.BFS(2);
}
}
Put image
Note that the above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex (example Disconnected graph). To print all the vertices, we can modify the BFS function to do traversal starting from all nodes one by one (Like the DFS modified version) .
Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment