Javatpoint Logo
Javatpoint Logo

Bridges in a Graph

Graph

A graph is a data structure where values are stored in the nodes, and nodes are connected to each other via edges. The graph may be connected or disconnected. If there is more than one component of a graph present, then the graph is known as a disconnected graph.

We can count the number of components in a graph using traversal (either BFS or DFS).

Bridges in a graph are those edges which create a unique path for the nodes. If removing an edge creates or divides a graph into more than one component, then that edge is known as a bridge.

We will be given the graph, and our task will be to print all the bridges of that graph if present.

For example:

Bridges in a Graph

In the above example, if you remove the edge between 2 and 4, then the graph will be disconnected, so it is a bridge.

Bridges in a Graph

Approach 1

The brute-force approach to this problem is that for each edge, we will remove that edge and check the number of components in a graph. If it is more than one, then we will add an edge into our answer, and we will add it again and check for the next edge.

Java code:

Output:

Bridges in a Graph

Explanation

In the above code, we created a graph as an adjacency matrix, and for each edge, we removed that edge and called the function to get the number of components. If the number of components is more than one, we will print the current edge as a bridge.

For getting the number of components, we used DFS starting from node 0 and then counted how many DFS calls we applied to get the number of components.

Time complexity: O(E*(N+E))

Space complexity: O(1)

Approach 2

We will use an optimal approach based on the initial time and minimum time to reach a node to determine the bridge edges in a graph.

We will use DFS (Depth First Search) Traversal for the graph, and if the node is unvisited, then we will update its insertion_time and minimum_time, and then we will call the DFS for its unvisited neighbors except its parent.

After the DFS call of the unvisited adjacent nodes, we will update the minimum_time of the current node. If the minimum_time of the adjacent node is greater than the insertion_time of the current node, then there is definitely a bridge edge between the node and the adjacent node, so that we will print it.

The reason for the above logic is that there is no path from the current node to the adjacent node except passing through the current node.

Java code:

Output:

Bridges in a Graph

Time complexity: O(N+E) to traverse the graph using DFS, where N is the number of nodes and E is the number of edges in the graph.

Space complexity: O(N)+O(N)+O(N) for using three arrays.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA