Skip to content

Instantly share code, notes, and snippets.

@ashwath10110
Created November 5, 2015 18:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashwath10110/5e0bc687f7a56ea43284 to your computer and use it in GitHub Desktop.
Save ashwath10110/5e0bc687f7a56ea43284 to your computer and use it in GitHub Desktop.
Simple Weighted and Directed Graph in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Programming.WeightedDirected
{
public class EdgeWeightedDigraph
{
private readonly int _v;
private int _e;
public LinkedList<DirectedEdge>[] adj;
public EdgeWeightedDigraph(int V)
{
this._v = V;
this._e = 0;
adj = new LinkedList<DirectedEdge>[V];
for (int v = 0; v < _v; v++)
{
adj[v] = new LinkedList<DirectedEdge>();
}
}
public int V()
{
return _v;
}
public int E()
{
return _e;
}
public void AddEdge(DirectedEdge e)
{
int v = e.From();
int w = e.To();
bool ExistsInV = adj[v].Contains(e);
if ((!ExistsInV))
{
adj[e.From()].AddFirst(e);
_e++;
}
}
public IEnumerable<DirectedEdge> Adj(int v)
{
return adj[v];
}
public IEnumerable<DirectedEdge> Edges()
{
LinkedList<DirectedEdge> linkedlist = new LinkedList<DirectedEdge>();
for (int v = 0; v < _v; v++)
{
foreach (DirectedEdge e in adj[v])
linkedlist.AddFirst(e);
}
return linkedlist;
}
public EdgeWeightedDigraph getTranspose()
{
EdgeWeightedDigraph input = this;
EdgeWeightedDigraph transpose = new EdgeWeightedDigraph(input.V());
for (int v = 0; v < input.V(); v++)
{
foreach (DirectedEdge e in input.Adj(v))
{
int current_start = e.From();
int current_end = e.To();
double current_weight = e.Weight();
DirectedEdge reverse = new DirectedEdge(current_end, current_start, current_weight);
transpose.adj[reverse.From()].AddFirst(reverse);
}
}
return transpose;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Programming.Data_Structures
{
public class DirectedEdge
{
private readonly int _v;
private readonly int _w;
private readonly double _weight;
public DirectedEdge(int v, int w, double weight)
{
this._v = v;
this._w = w;
this._weight = weight;
}
public double Weight()
{
return _weight;
}
public int From()
{
return _v;
}
public int To()
{
return _w;
}
public override string ToString()
{
return String.Format("{0:d}->{1:d} {2:f}", _v, _w, _weight);
}
}
}