Solution Review: Implement Breadth First Search
This review provides a detailed analysis of the different ways to solve the "Implement Breadth First Search" challenge.
We'll cover the following...
Solution: Using queues
Press + to interact
main.cs
LinkedList.cs
Graph.cs
using System;using System.Collections.Generic;namespace chapter_5{class Challenge_1{static void bfsTraversal_helper(Graph g, int source, bool[] visited, ref string result){if (g.getVertices() < 1){return;}//Create Queue(Implemented in previous chapters) for Breadth First Traversal and enqueue source in it//myQueue queue(g.getVertices());Queue<int> queue = new Queue<int> { };queue.Enqueue(source);visited[source] = true;int current_node;//Traverse while queue is not emptywhile (queue.Count != 0){//Dequeue a vertex/node from queue and add it to resultcurrent_node = queue.Dequeue();result += current_node.ToString();//Get adjacent vertices to the current_node from the array,//and if they are not already visited then enqueue them in the QueueLinkedList.Node temp = (g.getArray())[current_node].GetHead();while (temp != null){if (!visited[temp.data]){queue.Enqueue(temp.data);visited[temp.data] = true; //Visit the current Node}temp = temp.nextElement;}} //end of while}static string bfsTraversal(Graph g){string result = "";//Bool Array to hold the history of visited nodes//Make a node visited whenever you push it into stackbool[] visited = new bool[g.getVertices()];for (int i = 0; i < g.getVertices(); i++){visited[i] = false;}for (int i = 0; i < g.getVertices(); i++){if (!visited[i])bfsTraversal_helper(g, i, visited, ref result);}visited = null;return result;}static void Main(string[] args){Graph g = new Graph(6);g.addEdge(1, 2);g.addEdge(1, 3);g.addEdge(2, 4);g.addEdge(2, 5);Console.WriteLine(bfsTraversal(g));}}}
For this ...