Interface

AddVertex(T data)

AddEdge(int from, int to)

DFS

BFS

MST

TopSort

PrintGraph


using System;
using System.Collections.Generic;
using System.Linq; namespace TestCase1.TestCase.GraphMatrix
{
public class Vertex<T>
{
public T Data
{
get;
set;
} public bool Visited
{
get;
set;
} public Vertex(T data)
{
this.Data = data;
this.Visited = false;
}
} public class GraphMatrix<T>
{
private int GraphSize = ; private List<Vertex<T>> Vertices
{
get;
set;
} private int[,] adjMatrix
{
get;
set;
} private int Capacity
{
get;
set;
} public GraphMatrix(int capacity)
{
this.Vertices = new List<Vertex<T>>();
this.Capacity = capacity;
this.adjMatrix = new int[capacity, capacity];
for (int i = ; i < capacity; i++)
{
for (int j = ; j < capacity; j++)
{
this.adjMatrix[i, j] = ;
}
}
} public void AddVertex(T data)
{
// ? need check
var result = this.Vertices.Where(t => t.Data.Equals(data)); if (result == null || !result.Any())
{
this.Vertices.Add(new Vertex<T>(data));
this.GraphSize++;
}
} public void AddEdge(int from, int to)
{
if (from >= this.GraphSize || to >= this.GraphSize)
{
throw new ArgumentException("index is out of graph size!");
} this.adjMatrix[from, to] = ;
this.adjMatrix[to, from] = ;
} public void AddDirectedEdge(int from, int to)
{
if (from >= this.GraphSize || to >= this.GraphSize)
{
throw new ArgumentException("index is out of graph size!");
} this.adjMatrix[from, to] = ;
} public void ShowVertex(Vertex<T> ver)
{
Console.WriteLine("Show vertext = {0}", ver.Data);
} public void InitVisit()
{
foreach (var v in this.Vertices)
{
v.Visited = false;
}
} public void PrintGraph()
{
for (int i = ; i < this.GraphSize; i++)
{
Console.WriteLine();
Console.Write("Vertex is {0}: ", this.Vertices[i].Data);
for (int j = ; j < this.GraphSize; j++)
{
if (this.adjMatrix[i, j] == )
{
Console.Write(this.Vertices[j].Data);
Console.Write(" ");
}
}
}
} public int FindVertexWithoutSuccssor()
{
for (int i = ; i < this.GraphSize; i++)
{
bool hasSuccessor = false;
for (int j = ; j < this.GraphSize; j++)
{
if (this.adjMatrix[i, j] == )
{
hasSuccessor = true;
break;
}
} if (!hasSuccessor)
{
return i;
}
} return -;
} public void MoveColumn(int column)
{
for (int row = ; row < this.GraphSize; row++)
{
for (int j = column + ; j < this.GraphSize; j++)
{
this.adjMatrix[row, j - ] = this.adjMatrix[row, j];
}
}
} public void MoveRow(int row)
{
for (int column = ; column < this.GraphSize; column++)
{
for (int j = row + ; j < this.GraphSize; j++)
{
this.adjMatrix[j - , column] = this.adjMatrix[j, column];
}
}
} public void RemoveVertex(int index)
{
this.Vertices.RemoveAt(index);
this.GraphSize--; // important here.
} public void TopSort()
{
Stack<Vertex<T>> stack = new Stack<Vertex<T>>(); while (this.GraphSize > )
{
int vertex = FindVertexWithoutSuccssor();
if (vertex == -)
{
throw new Exception("The graph has cycle!");
} stack.Push(this.Vertices[vertex]); this.MoveRow(vertex);
this.MoveColumn(vertex);
this.RemoveVertex(vertex);
} while (stack.Count != )
{
var ret = stack.Pop();
Console.WriteLine(ret.Data);
}
} public void DFS()
{
Stack<int> stack = new Stack<int>(); // validation
if (this.GraphSize == )
{
Console.WriteLine("graph is empty, no op!");
return;
} stack.Push();
this.Vertices[].Visited = true;
ShowVertex(this.Vertices[]); while (stack.Count != )
{
int index = stack.Peek(); // find next un-visited edge
int v = this.GetNextUnVisitedAdjancentNode(index);
if (v == -)
{
stack.Pop();
}
else
{
this.ShowVertex(this.Vertices[v]);
this.Vertices[v].Visited = true;
stack.Push(v);
}
} // reset ALL VISIT flags
this.InitVisit();
} public void BFS()
{
Queue<int> queue = new Queue<int>(); // validation
if (this.GraphSize == )
{
return;
} // logic
queue.Enqueue();
ShowVertex(this.Vertices[]);
this.Vertices[].Visited = true; while (queue.Count > )
{
int result = queue.Dequeue(); // find adjacent nodes and enqueue them
for (int j = ; j < this.GraphSize; j++)
{
if (adjMatrix[result, j] == && this.Vertices[j].Visited == false)
{
// print all adjacent nodes
ShowVertex(this.Vertices[j]);
this.Vertices[j].Visited = true; queue.Enqueue(j);
}
}
} // reset
this.InitVisit();
} public void MST()
{
// validation
if (this.GraphSize == )
{
return;
} // init
Stack<int> stack = new Stack<int>();
stack.Push();
int currentVertex = ;
int vertex = ; this.Vertices[].Visited = true; while (stack.Count > )
{
currentVertex = stack.Peek(); vertex = this.GetNextUnVisitedAdjancentNode(currentVertex);
if (vertex == -)
{
stack.Pop();
}
else
{
this.Vertices[vertex].Visited = true; // print
Console.Write(this.Vertices[currentVertex].Data.ToString() + this.Vertices[vertex].Data.ToString());
Console.Write("-> ");
stack.Push(vertex);
}
} // clean up
this.InitVisit();
} private int GetNextUnVisitedAdjancentNode(int v)
{
// validation
if (v >= this.GraphSize)
{
throw new Exception("v is out of graph size!");
} for (int i = ; i < this.GraphSize; i++)
{
if (adjMatrix[v, i] == && !this.Vertices[i].Visited)
{
return i;
}
} return -;
} public void DepthFirstSearch()
{
DFSUtil();
this.InitVisit();
} private void DFSUtil(int vertex)
{
// validation
if (vertex >= this.GraphSize)
{
throw new ArgumentException("out of graph size!");
} int ver = this.GetNextUnVisitedAdjancentNode(vertex);
if (ver == -)
{
return;
}
else
{
// print current node
ShowVertex(this.Vertices[ver]);
this.Vertices[ver].Visited = true; DFSUtil(ver);
}
}
}
}

Adjacency matrix based Graph的更多相关文章

  1. Convert Adjacency matrix into edgelist

    Convert Adjacency matrix into edgelist import numpy as np #read matrix without head. a = np.loadtxt( ...

  2. 路径规划 Adjacency matrix 传球问题

    建模 问题是什么 知道了问题是什么答案就ok了 重复考虑 与 重复计算 程序可以重复考虑  但往目标篮子中放入时,放不放把握好就ok了. 集合 交集 并集 w 路径规划 字符串处理 42423 424 ...

  3. 论文解读SDCN《Structural Deep Clustering Network》

    前言 主体思想:深度聚类需要考虑数据内在信息以及结构信息. 考虑自身信息采用 基础的 Autoencoder ,考虑结构信息采用 GCN. 1.介绍 在现实中,将结构信息集成到深度聚类中通常需要解决以 ...

  4. Paper: A Novel Time Series Forecasting Method Based on Fuzzy Visibility Graph

    Problem define a fuzzy visibility graph (undirected weighted graph), then give a new similarity meas ...

  5. Introduction to graph theory 图论/脑网络基础

    Source: Connected Brain Figure above: Bullmore E, Sporns O. Complex brain networks: graph theoretica ...

  6. 论文解读(GraRep)《GraRep: Learning Graph Representations with Global Structural Information》

    论文题目:<GraRep: Learning Graph Representations with Global Structural Information>发表时间:  CIKM论文作 ...

  7. UVa 10720 - Graph Construction(Havel-Hakimi定理)

    题目链接: 传送门 Graph Construction Time Limit: 3000MS     Memory Limit: 65536K Description Graph is a coll ...

  8. UVA 10720 Graph Construction 贪心+优先队列

    题目链接: 题目 Graph Construction Time limit: 3.000 seconds 问题描述 Graph is a collection of edges E and vert ...

  9. 那些年我们写过的三重循环----CodeForces 295B Greg and Graph 重温Floyd算法

    Greg and Graph time limit per test 3 seconds memory limit per test 256 megabytes input standard inpu ...

随机推荐

  1. ldap 导出、导入ldif数据

    ldap 导出.导入ldif数据有如下方式: 1.dsadm(速度快,需要停止ldap实例) 2.dsconf(速度慢,需要保持ldap实例开启) windows导出.导入需要加上参数--unsecu ...

  2. Charles在Mac、iPhone、Android上抓http/https协议的包

    1.我使用的版本是4.0.2,下载和破解网上方法很多,不做说明 2.Charles在Mac上抓http/https协议的包 2.1先把这三个都给装上,装完后会自动跳转到钥匙串中 2.2如果装完后提示证 ...

  3. 以数之名:In Praise of APL 后记

    原文:http://www.jsoftware.com/papers/perlis77.htm 标题:In Praise of APL: A Language for Lyrical Programm ...

  4. 关于:无法创建链接服务器 "ORCL" 的 OLE DB 访问接口 "OraOLEDB.Oracle" 的实例 (错误:7302)

    本人接触和使用Oracle数据库才有一个季度的时间,问题比较白,大神请无视本文. 环境: 1.数据服务器,windows2008R2,Oracle11g 2.报表服务器,windows2008R2,S ...

  5. Mac搭建SVN服务器+Cornerstone连接服务器

    Mac自带svn,我们只需配置并开启就可以了,打开终端,输入svnserve --version查看svn版本 可以看到我的mac自带的svn版本号为1.9.7,下面开始配置服务器: 1.终端输入su ...

  6. Oracle 11g 单实例到单实例OGG同步实施文档-EXPDP初始化

    Oracle 11g 单实例到单实例OGG同步实施文档-EXPDP初始化 2018-06-07 00:446470原创GoldenGate 作者: leo 本文链接:https://www.cndba ...

  7. C#中枚举的使用

    一.什么是枚举类型 枚举类型(也称为枚举):该类型可以是除 char以外的任何整型(重点). 枚举元素的默认基础类型为 int.准许使用的枚举类型有 byte.sbyte.short.ushort.i ...

  8. Scrapy的piplines.py存储文件和存储mongodb

    一.将数据保存到文件 1.piplines.py文件 import json class TencentPipeline(object): def open_spider(self,spider): ...

  9. μCOS-Ⅲ——临界段

    临界段代码(critical sections),也叫临界区(critical region),是指那些必须完整连续运行,不可被打断的代码段.μC/OS-Ⅲ系统中存在大量临界段代码.采用两种方式对临界 ...

  10. input(Text)控件作为填空输入,但运行后,有曾经输入的记录显示,用autocomplete="off"解决

    系统中,有设计填空题,原来程序中,用input(Text)控件,   <input type="text" name="NO<%=rs("id&qu ...