Skip to content

Instantly share code, notes, and snippets.

@ashwath10110
Created November 5, 2015 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashwath10110/9e16bdb6ab2731d9bcca to your computer and use it in GitHub Desktop.
Save ashwath10110/9e16bdb6ab2731d9bcca to your computer and use it in GitHub Desktop.
Simple Unweighted Undirected in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Programming.Data_Structures
{
public class Graph
{
public readonly int _V;
private int _E;
public LinkedList<int>[] adj;
public Graph(int V = 0)
{
if (V < 0)
throw new Exception("-ve V");
this._V = V;
adj = new LinkedList<int>[V];
for (int i = 0; i < V; i++)
{
adj[i] = new LinkedList<int>();
}
}
public int V()
{
return this._V;
}
public int E()
{
return this._E;
}
public void AddEdge(int v, int w)
{
if (v < 0 || v >= _V) throw new Exception("Out of bounds");
if (w < 0 || w >= _V) throw new Exception("Out of bounds");
bool ExistsInV = adj[v].Contains(w);
bool ExistsInW = adj[w].Contains(v);
if ((!ExistsInV) && (!ExistsInW))
{
adj[v].AddFirst(w);
adj[w].AddFirst(v);
_E++;
}
}
public IEnumerable<int> Adj(int V)
{
return adj[V];
}
public override String ToString()
{
StringBuilder s = new StringBuilder();
string NEWLINE = Environment.NewLine;
s.Append(_V + " vertices, " + _E + " edges " + NEWLINE);
for (int i = 0; i < _V; i++)
{
s.Append(i + ": ");
foreach (int item in adj[i])
{
s.Append(item + " ");
}
s.Append(NEWLINE);
}
return s.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment