首页 > 代码库 > 数据结构之图 Part2 - 1

数据结构之图 Part2 - 1

邻接矩阵

网上很少有C# 写图的数据结构的例子,实际的项目中也从来没用过Array 这坨东西,随手写个,勿喷。

namespace LH.GraphConsole{    public struct Graph    {        public Graph(int vertexNumber, int edgeNumber)        {            VertexNumber = vertexNumber;            EdgeNumber = edgeNumber;            Vertexs = new string[VertexNumber];            Edges = new int[VertexNumber, VertexNumber];            for (int i = 0; i < VertexNumber; i++)            {                for (int j = 0; j < VertexNumber; j++)                {                    Edges[i, j] = int.MaxValue;                }            }        }        public String[] Vertexs { get; set; }        public int[,] Edges { get; set; }        private int VertexNumber { get; set; }        private int EdgeNumber { get; set; }        }}

然后是简单的主程序代码:

namespace LH.GraphConsole{    class Program    {        static void Main(string[] args)        {            var vertexNumber = 5;            var edgeNumber = 6;            Graph graph = new Graph(vertexNumber, edgeNumber);            graph.Vertexs[0] = "v0";            graph.Vertexs[1] = "v1";            graph.Vertexs[2] = "v2";            graph.Vertexs[3] = "v3";            graph.Vertexs[4] = "v4";            graph.Edges[1, 2] = 3;            graph.Edges[1, 0] = 9;            graph.Edges[2, 0] = 2;            graph.Edges[2, 3] = 5;            graph.Edges[3, 4] = 1;        }    }}

当然了,这种数据结构简明易懂,可惜的是对于比较稀疏的图,白白浪费了很多空间。

下一回合我们来看邻接表的C#写法。