I was asked to implement a graph and BFS and DFS.
Please comment. Is it understandable? Is my algorithm correct? Are there any optimizations?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Graph
{
public List<Node> list;
public Graph()
{
list = new List<Node>();
}
}
public class Node
{
public int Index { get; set; }
public List<Node> neighbors;
public Node(int index)
{
Index = index;
neighbors = new List<Node>();
}
public void AddNeighbor(int index)
{
neighbors.Add(new Node(index));
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class BFS
{
public BFS()
{
Graph graph = new Graph();
graph.list.Add(new Node(0));
graph.list.ElementAt<Node>(0).AddNeighbor(1);
graph.list.ElementAt<Node>(0).AddNeighbor(2);
graph.list.ElementAt<Node>(0).neighbors.ElementAt<Node>(0).AddNeighbor(3);
GraphTraverseBFS(graph);
}
public void GraphTraverseBFS(Graph graph)
{
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(graph.list[0]);
while(queue.Count > 0)
{
Node tempNode = queue.Dequeue();
Console.WriteLine("Node number: " +tempNode.Index);
foreach (var item in tempNode.neighbors)
{
queue.Enqueue(item);
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class DFS
{
public Graph graph { get; set; }
public DFS()
{
graph = new Graph();
graph.list.Add(new Node(0));
graph.list.ElementAt<Node>(0).AddNeighbor(1);
graph.list.ElementAt<Node>(0).AddNeighbor(2);
graph.list.ElementAt<Node>(0).neighbors.ElementAt<Node>(0).AddNeighbor(3);
GraphTraverseDFS(graph);
}
public void GraphTraverseDFS(Graph graph)
{
Stack<Node> stack = new Stack<Node>();
stack.Push(graph.list[0]);
while (stack.Count != 0)
{
Node tempNode = stack.Pop();
Console.WriteLine("Node number: " + tempNode.Index);
var negibours = tempNode.neighbors;
foreach (var item in negibours)
{
stack.Push(item);
}
}
}
}
}