Solution Review: Find a "Mother Vertex" in a Graph
This review provides a detailed analysis of the different ways to solve the "Find a 'Mother Vertex' in a Graph" challenge.
We'll cover the following...
Solution #1: Naive solution
Press + to interact
main.cs
LinkedList.cs
Graph.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace chapter_5{class Challenge_4_1{static int performDFS(Graph g, int source) {int num_of_vertices = g.getVertices();int vertices_reached = 0; //To store how many vertices reached starting from source//Bool Array to hold the history of visited nodes//Make a node visited whenever you push it into stackbool [] visited = new bool[num_of_vertices];//Create Stack(Implemented in previous lesson) for Depth First Traversal and Push source in itStack <int>stack = new Stack<int>();stack.Push(source);visited[source] = true;//Traverse while stack is not emptyint current_node;while (stack.Count != 0) {//Pop a vertex/node from stackcurrent_node = stack.Pop();//Get adjacent vertices to the current_node from the array,//and if only push unvisited adjacent vertices into stackLinkedList.Node temp = (g.getArray())[current_node].GetHead();while (temp != null) {if (!visited[temp.data]) {stack.Push(temp.data);visited[temp.data] = true;vertices_reached++;}temp = temp.nextElement;}} //end of whilevisited = null;return vertices_reached + 1; //+1 to include the source itself.}static int findMotherVertex(Graph g){//Traverse the Graph Array and perform DFS operation on each vertex//The vertex whose DFS Traversal results is equal to the total number//of vertices in graph is a mother vertexint num_of_vertices_reached = 0;for (int i = 0; i < g.getVertices(); i++) {num_of_vertices_reached = performDFS(g, i);if (num_of_vertices_reached == g.getVertices()){return i;}}return - 1;}static void Main(string[] args){Graph g = new Graph(4);g.addEdge(0, 1);g.addEdge(1, 2);g.addEdge(3, 0);g.addEdge(3, 1);Console.WriteLine(findMotherVertex(g));}}}
This is the brute force approach for solving this problem. Run a DFS on each vertex using DFS
, and keep track of the number of vertices ...