Skip to content

Instantly share code, notes, and snippets.

@phillipsj
Created February 10, 2021 02:46
Show Gist options
  • Save phillipsj/b05b1c528b2dee26dfc40f1d5c0eb6dc to your computer and use it in GitHub Desktop.
Save phillipsj/b05b1c528b2dee26dfc40f1d5c0eb6dc to your computer and use it in GitHub Desktop.
Example for doing Graph stuff in .NET Core
using System;
using System.Collections.Generic;
using System.Linq;
namespace Graph {
public class Vertex {
public string Value { get; }
public List<Vertex> AdjacentVertices { get; }
public Vertex(string value) {
Value = value;
AdjacentVertices = new List<Vertex>();
}
public void AddAdjacentVertex(Vertex vertex) {
if (AdjacentVertices.Contains(vertex)) return;
AdjacentVertices.Add(vertex);
vertex.AdjacentVertices.Add(this);
}
}
class Program {
static void Main(string[] args) {
Console.WriteLine("Hello World!");
}
public void DfsTraverse(Vertex vertex, Dictionary<string, bool> visistedVertices) {
visistedVertices[vertex.Value] = true;
Console.WriteLine(vertex.Value);
foreach (var adjacentVertex in vertex.AdjacentVertices.Where(adjacentVertex =>
!visistedVertices.ContainsKey(vertex.Value))) {
DfsTraverse(adjacentVertex, visistedVertices);
}
}
public void BfsTraverse(Vertex startingVertex) {
var queue = new Queue<Vertex>();
var visitedVertices = new Dictionary<string, bool>();
visitedVertices[startingVertex.Value] = true;
queue.Enqueue(startingVertex);
while (queue.Count > 0) {
var currentVertex = queue.Dequeue();
Console.WriteLine(currentVertex.Value);
foreach (var adjacentVertex in currentVertex.AdjacentVertices.Where(adjacentVertex =>
!visitedVertices.ContainsKey(adjacentVertex.Value))) {
visitedVertices[adjacentVertex.Value] = true;
queue.Enqueue(adjacentVertex);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment