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 ...
随机推荐
- webpack基本配置文件(含解释)
const path = require('path'); // 以下文件需要npm i 文件名 --save-dev const uglify = require('uglifyjs-webpack ...
- element-ui <el-input> 注册keyup事件,即键盘enter.
<template> <!-- 需求:keyup事件一般用在input中,在input框中输入内容,用户点击键盘的enter,执行搜索 --> <div class=&q ...
- Hive - - 分组求最大,最小(加行键)
Hive - - 分组求最大,最小(加行键) 数据: 1325927 陕西 汉中 084 08491325928 陕西 汉中 084 08491325930 陕西 延安 084 08421325931 ...
- ELK快速部署及使用~
Elastic Stack 开发人员不能登陆线上服务器查看详细日志 各个系统都有日志,日志数据分散难以查找 日志数据量大,查询速度慢,或者数据不够实时 官网地址:https://www.elastic ...
- MongoDB之 分组查询
分组查询 可视化工具 https://robomongo.org pymongo from pymongo import MongoClient # 方式一: c = MongoClient(host ...
- There are multiple modules with names that only differ in casing. 黄色warning
There are multiple modules with names that only differ in casing.有多个模块同名仅大小写不同This can lead to unexp ...
- day2 购物车
需求: 商家入口: 1.商品列表永久保存(暂时使用存储在文件,也可以使用sqlite)里. 2.商家可以增加商品,也可以修改商品价格 买家入口: 1.购物车信息永久保存,暂时使用存储在文件,也可以使用 ...
- nginx 日志打印post请求参数
在日志格式后面加上 $request_body 配置信息 log_format main '$remote_addr - $remote_user [$time_local] "$reque ...
- 使用Spark进行搜狗日志分析实例——列出搜索不同关键词超过10个的用户及其搜索的关键词
package sogolog import org.apache.hadoop.io.{LongWritable, Text} import org.apache.hadoop.mapred.Tex ...
- 19.Scharr滤波器
//Scharr void Test_Scharr() { Mat grad_x,grad_y; Mat abs_grad_x,abs_grad_y,dst; g_srcImage=imread(&q ...