Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
866 changes: 866 additions & 0 deletions Graphs/Hard/README.md

Large diffs are not rendered by default.

126 changes: 126 additions & 0 deletions Graphs/Hard/bridge_edge.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
#include <iostream>
#include <list>
#include <vector>

class Graph
{
int V; // Number of vertices
std::list<int> *adj; // Adjacency list to represent the graph

// Utility function to find bridges using DFS traversal
void bridgeUtil(int u, std::vector<bool> &visited, std::vector<int> &disc,
std::vector<int> &low, int parent);

public:
Graph(int V); // Constructor
void addEdge(int v, int w); // Add an edge to the graph
void bridge(); // Find and print all bridges
};

Graph::Graph(int V)
{
this->V = V;
adj = new std::list<int>[V];
}

void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v); // Graph is undirected
}

void Graph::bridgeUtil(int u, std::vector<bool> &visited, std::vector<int> &disc,
std::vector<int> &low, int parent)
{
static int time = 0; // Static variable for simplicity

// Mark the current node as visited
visited[u] = true;

// Initialize discovery time and low value
disc[u] = low[u] = ++time;

// Explore all neighbors of the current node
for (int v : adj[u])
{
if (v == parent) // Skip the edge to the parent
continue;

if (visited[v])
{
// If v is already visited, update the low value of u
low[u] = std::min(low[u], disc[v]);
}
else
{
// Recur for the unvisited neighbor
bridgeUtil(v, visited, disc, low, u);

// Update the low value of u
low[u] = std::min(low[u], low[v]);

// Check for a bridge and store it
if (low[v] > disc[u])
std::cout << "Bridge: " << u << " " << v << std::endl;
}
}
}

void Graph::bridge()
{
std::vector<bool> visited(V, false);
std::vector<int> disc(V, -1);
std::vector<int> low(V, -1);

std::cout << "\nBridges in the graph:\n";

// Call the recursive helper function for each unvisited vertex
for (int i = 0; i < V; ++i)
{
if (!visited[i])
{
bridgeUtil(i, visited, disc, low, -1);
}
}
}

int main()
{
int vertices, edges;
std::cout << "Enter the number of vertices: ";
std::cin >> vertices;

std::cout << "Enter the number of edges: ";
std::cin >> edges;

std::cout << "\nEnter the edges (format: vertex1 vertex2):\n";
Graph g(vertices);
for (int i = 0; i < edges; ++i)
{
int v, w;
std::cin >> v >> w;
g.addEdge(v, w);
}

g.bridge();

return 0;
}

// Enter the number of vertices: 8
// Enter the number of edges: 10
// Enter the edges (format: vertex1 vertex2):
// 0 1
// 1 2
// 2 0
// 1 3
// 3 4
// 4 5
// 5 3
// 6 7
// 7 6
// 5 6
// Bridges in the graph:
// 6 7
// 5 6
// 1 3
122 changes: 122 additions & 0 deletions Graphs/Hard/bridge_edge.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import java.util.*;

public class bridge_edge {
private static class Graph {
private int V; // Number of vertices
private LinkedList<Integer> adj[]; // Adjacency list to represent the graph
private int time = 0;
private static final int NIL = -1;

// Constructor
@SuppressWarnings("unchecked")
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList<>();
}

// Function to add an edge into the graph
void addEdge(int v, int w) {
adj[v].add(w); // Add w to v's list.
adj[w].add(v); // Add v to w's list
}

// A recursive function that finds and prints bridges using DFS traversal
void bridgeUtil(int u, boolean visited[], int disc[], int low[], int parent[]) {
// Mark the current node as visited
visited[u] = true;

// Initialize discovery time and low value
disc[u] = low[u] = ++time;

// Go through all vertices adjacent to this
Iterator<Integer> i = adj[u].iterator();
while (i.hasNext()) {
int v = i.next(); // v is the current adjacent of u

// If v is not visited yet, then make it a child of u in DFS tree and recur for
// it.
// If v is not visited yet, then recur for it
if (!visited[v]) {
parent[v] = u;
bridgeUtil(v, visited, disc, low, parent);

// Check if the subtree rooted with v has a connection to one of the ancestors
// of u
low[u] = Math.min(low[u], low[v]);

// If the lowest vertex reachable from the subtree under v is below u in DFS
// tree, then u-v is a bridge
if (low[v] > disc[u])
System.out.println(u + " " + v);
}

// Update the low value of u for parent function calls.
else if (v != parent[u])
low[u] = Math.min(low[u], disc[v]);
}
}

// DFS based function to find all bridges. It uses the recursive function
// bridgeUtil()
void bridge() {
// Mark all the vertices as not visited
boolean visited[] = new boolean[V];
int disc[] = new int[V];
int low[] = new int[V];
int parent[] = new int[V];

// Initialize parent and visited arrays
Arrays.fill(parent, NIL);

// Call the recursive helper function to find Bridges in DFS tree rooted with
// vertex 'i'
for (int i = 0; i < V; i++)
if (!visited[i])
bridgeUtil(i, visited, disc, low, parent);
}
}

public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of vertices: ");
int vertices = scanner.nextInt();

Graph g = new Graph(vertices);

System.out.print("Enter the number of edges: ");
int edges = scanner.nextInt();

System.out.println("Enter the edges (format: vertex1 vertex2):");
for (int i = 0; i < edges; i++) {
int v = scanner.nextInt();
int w = scanner.nextInt();
g.addEdge(v, w);
}

System.out.println("Bridges in the graph:");
g.bridge();

scanner.close();
}
}

// Enter the number of vertices: 8
// Enter the number of edges: 10
// Enter the edges (format: vertex1 vertex2):
// 0 1
// 1 2
// 2 0
// 1 3
// 3 4
// 4 5
// 5 3
// 6 7
// 7 6
// 5 6
// Bridges in the graph:
// 6 7
// 5 6
// 1 3
90 changes: 90 additions & 0 deletions Graphs/Hard/bridge_edge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
from collections import defaultdict

class Graph:
def __init__(self, vertices):
# Initialize a graph with the given number of vertices
self.V = vertices
# Create a defaultdict to represent an adjacency list for the graph
self.graph = defaultdict(list)

def add_edge(self, u, v):
# Add an undirected edge between vertices u and v
self.graph[u].append(v)
self.graph[v].append(u)

def find_bridges(self):
# List to store bridges found in the graph
bridges = []

def bridge_util(current, visited, parent, low, disc):
nonlocal bridges
# Mark the current node as visited
visited[current] = True
# Set discovery time and low value for the current node
disc[current] = low[current] = self.time
self.time += 1

for neighbor in self.graph[current]:
if not visited[neighbor]:
# Recur for the unvisited neighbor
parent[neighbor] = current
bridge_util(neighbor, visited, parent, low, disc)

# Update low value
low[current] = min(low[current], low[neighbor])

# Check for a bridge
if low[neighbor] > disc[current]:
bridges.append((current, neighbor))
elif neighbor != parent[current]:
# Update low value for the visited neighbor
low[current] = min(low[current], disc[neighbor])

# Initialize data structures
visited = [False] * self.V
parent = [-1] * self.V
low = [float('inf')] * self.V
disc = [float('inf')] * self.V
self.time = 0

# Call the bridge utility function for each unvisited vertex
for vertex in range(self.V):
if not visited[vertex]:
bridge_util(vertex, visited, parent, low, disc)

return bridges

# Prompt user input for the graph
num_vertices = int(input("Enter the number of vertices: "))
g1 = Graph(num_vertices)

num_edges = int(input("Enter the number of edges: "))
print("Enter the edges (format: vertex1 vertex2):")
for _ in range(num_edges):
edge_input = input().split()
edge = tuple(map(int, edge_input))
g1.add_edge(*edge)

# Find and print bridges
print("\nBridges in the graph:")
bridges = g1.find_bridges()
for bridge in bridges:
print(bridge)

# Enter the number of vertices: 8
# Enter the number of edges: 10
# Enter the edges (format: vertex1 vertex2):
# 0 1
# 1 2
# 2 0
# 1 3
# 3 4
# 4 5
# 5 3
# 6 7
# 7 6
# 5 6
# Bridges in the graph:
# 6 7
# 5 6
# 1 3
Loading