Adjacency matrix based Graph
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的更多相关文章
- Convert Adjacency matrix into edgelist
Convert Adjacency matrix into edgelist import numpy as np #read matrix without head. a = np.loadtxt( ...
- 路径规划 Adjacency matrix 传球问题
建模 问题是什么 知道了问题是什么答案就ok了 重复考虑 与 重复计算 程序可以重复考虑 但往目标篮子中放入时,放不放把握好就ok了. 集合 交集 并集 w 路径规划 字符串处理 42423 424 ...
- 论文解读SDCN《Structural Deep Clustering Network》
前言 主体思想:深度聚类需要考虑数据内在信息以及结构信息. 考虑自身信息采用 基础的 Autoencoder ,考虑结构信息采用 GCN. 1.介绍 在现实中,将结构信息集成到深度聚类中通常需要解决以 ...
- 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 ...
- Introduction to graph theory 图论/脑网络基础
Source: Connected Brain Figure above: Bullmore E, Sporns O. Complex brain networks: graph theoretica ...
- 论文解读(GraRep)《GraRep: Learning Graph Representations with Global Structural Information》
论文题目:<GraRep: Learning Graph Representations with Global Structural Information>发表时间: CIKM论文作 ...
- UVa 10720 - Graph Construction(Havel-Hakimi定理)
题目链接: 传送门 Graph Construction Time Limit: 3000MS Memory Limit: 65536K Description Graph is a coll ...
- UVA 10720 Graph Construction 贪心+优先队列
题目链接: 题目 Graph Construction Time limit: 3.000 seconds 问题描述 Graph is a collection of edges E and vert ...
- 那些年我们写过的三重循环----CodeForces 295B Greg and Graph 重温Floyd算法
Greg and Graph time limit per test 3 seconds memory limit per test 256 megabytes input standard inpu ...
随机推荐
- javascript 判断质数
1.判断n是否为number类型,是否为整数,是否小于2: 2.若n == 2返回true: 3.从3至n的算术平方根(square)之间的奇数,如果n取余为0,则不是奇数. var isPrime ...
- 小程序中通过判断id来删除数据,当数据长度为0时,显示隐藏部分(交流QQ群:604788754)
欢迎加入小程序交流群:本群定期更新在工作种遇到的小知识(交流QQ群:604788754) WXML: <!--遍历循环的数据部分--> <block wx:for="{{d ...
- Ceres Solver 入门稍微多一点
其实ceres solver用了挺多的,可能是入门不精,有时候感觉感觉不理解代码上是怎么实现的,这次就通过ceres的官网仔细看了一些介绍,感觉对cpp了解更好了一些. 跟g2o的比较的话,感觉cer ...
- IoT experitment
Abstract: In order to solve the problems of complex experiment management, complicated teaching task ...
- mpeg4文件分析(纯c解析代码)
参考链接: 1. MPEG4码流的帧率计算 https://blog.csdn.net/littlebee90/article/details/68924690 2. M ...
- js插件ztree使用
最新给公司后台写了一个配置页面,在网上搜到一个js插件ztree,记录一下使用心得. 首先说一下ztree官网,好多方法我都是从官网api上学习的,官网地址http://www.treejs.cn/v ...
- Java面试2018常考题目汇总
一.JAVA基础篇-概念 1.简述你所知道的Linux: Linux起源于1991年,1995年流行起来的免费操作系统,目前, Linux是主流的服务器操作系统, 广泛应用于互联网.云计算.智能手机( ...
- 递归实现列出当前工程下所有.Java文件
package com.lanxi.demo2_3; import java.io.File; import java.util.ArrayList; import java.util.List; / ...
- [linux-脚本]shebang(shabang #!)
使用Linux或者unix系统的人们对#!这个符号都不陌生,但要说出个具体的所以然来,很多人估计还真不行,我们有必要就此整理一下.Shebang这个符号通常在Unix系统的脚本中第一行开头中写到,它指 ...
- servlet中常用到的工具
1. 解析ajax传来的json字符串,得到json对象 private JSONObject getJsonObject(HttpServletRequest req) { StringBuffer ...