...

/

Solution: Check if Removing Given Edge Creates Components in Graph

Solution: Check if Removing Given Edge Creates Components in Graph

This review provides a detailed analysis of the solution to remove a given edge from a graph.

We'll cover the following...

Solution: Using Graph Traversal

Press + to interact
main.cpp
Graph.cpp
Graph.h
#include "Graph.h"
bool Graph::isConnected() {
vector <bool> visited(this -> vertices, false);
// Using depth first traversal (Already implemented in previous challenge)
depthFirstTraversal(0, visited);
// if there are unvisited vertices then graph is divided into components
for (int i = 1; i < this -> vertices; i++)
if (visited[i] == false)
return false;
return true;
}
bool Graph::willCauseSeparateComponents(int source, int destination) {
// remove the edge from both sides because graph is bidirectional
adjacencyList[source].remove(destination);
adjacencyList[destination].remove(source);
//check whether the graph is connected or not
bool result = isConnected();
if(result == false) //if graph is not connected then components created
return true;
else
return false;
}
int main() {
Graph g(5);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(0, 4);
// remove edge 3 -> 4
if(g.willCauseSeparateComponents(3, 4))
cout << "Yes, separate components created due to deletion of edge 3 -> 4" << endl;
else
cout << "No, separate components not created due to deletion of edge 3 -> 4"<< endl;
// remove edge 1 -> 2
if(g.willCauseSeparateComponents(1, 2))
cout << "Yes, separate components created due to deletion of edge 1 -> 2"<< endl;
else
cout << "No, separate components not created due to deletion of edge 1 -> 2"<< endl;
return 0;
}

This is a fairly simple challenge. Just check if the graph remains connected after removal of the specified edge or not, then traverse the graph. If there is a vertex not visited, then separate ...