算法系列15天速成——第十五天 图【下】(大结局)

时间:2022-06-21 06:28:28

今天是大结局,说下“图”的最后一点东西,“最小生成树“和”最短路径“。

一: 最小生成树

1. 概念

    首先看如下图,不知道大家能总结点什么。

    对于一个连通图g,如果其全部顶点和一部分边构成一个子图g1,当g1满足:

       ① 刚好将图中所有顶点连通。②顶点不存在回路。则称g1就是g的“生成树”。

           其实一句话总结就是:生成树是将原图的全部顶点以最小的边连通的子图,这不,如下的连通图可以得到下面的两个生成树。

       ② 对于一个带权的连通图,当生成的树不同,各边上的权值总和也不同,如果某个生成树的权值最小,则它就是“最小生成树”。

     算法系列15天速成——第十五天 图【下】(大结局)

2. 场景

      实际应用中“最小生成树”还是蛮有实际价值的,教科书上都有这么一句话,若用图来表示一个交通系统,每一个顶点代表一个城市,

  边代表两个城市之间的距离,当有n个城市时,可能会有n(n-1)/2条边,那么怎么选择(n-1)条边来使城市之间的总距离最小,其实它

  的抽象模型就是求“最小生成树”的问题。

 

3. prim算法

    当然如何求“最小生成树”问题,前人都已经给我们总结好了,我们只要照葫芦画瓢就是了,

    第一步:我们建立集合“v,u",将图中的所有顶点全部灌到v集合中,u集合初始为空。

    第二步: 我们将v1放入u集合中并将v1顶点标记为已访问。此时:u(v1)。

    第三步: 我们寻找v1的邻接点(v2,v3,v5),权值中发现(v1,v2)之间的权值最小,此时我们将v2放入u集合中并标记v2为已访问,

                此时为u(v1,v2)。

    第四步: 我们找u集合中的v1和v2的邻接边,一阵痉挛后,发现(v1,v5)的权值最小,此时将v5加入到u集合并标记为已访问,此时

                 u的集合元素为(v1,v2,v5)。

    第五步:此时我们以(v1,v2,v5)为基准向四周寻找最小权值的邻接边,发现(v5,v4)的权值最小,此时将v4加入到u集合并标记

                 为已访问,此时u的集合元素为(v1,v2,v5,v4)。

    第六步: 跟第五步形式一样,找到了(v1,v3)的权值最小,将v3加入到u集合中并标记为已访问,最终u的元素为(v1,v2,v5,v4,v3),

最终发现顶点全部被访问,最小生成树就此诞生。
 

复制代码 代码如下:


#region prim算法获取最小生成树
        /// <summary>
/// prim算法获取最小生成树
/// </summary>
/// <param name="graph"></param>
        public void prim(matrixgraph graph, out int sum)
        {
            //已访问过的标志
            int used = 0;

 

            //非邻接顶点标志
            int noadj = -1;

            //定义一个输出总权值的变量
            sum = 0;

            //临时数组,用于保存邻接点的权值
            int[] weight = new int[graph.vertexnum];

            //临时数组,用于保存顶点信息
            int[] tempvertex = new int[graph.vertexnum];

            //取出邻接矩阵的第一行数据,也就是取出第一个顶点并将权和边信息保存于临时数据中
            for (int i = 1; i < graph.vertexnum; i++)
            {
                //保存于邻接点之间的权值
                weight[i] = graph.edges[0, i];

                //等于0则说明v1与该邻接点没有边
                if (weight[i] == short.maxvalue)
                    tempvertex[i] = noadj;
                else
                    tempvertex[i] = int.parse(graph.vertex[0]);
            }

            //从集合v中取出v1节点,只需要将此节点设置为已访问过,weight为0集合
            var index = tempvertex[0] = used;
            var min = weight[0] = short.maxvalue;

            //在v的邻接点中找权值最小的节点
            for (int i = 1; i < graph.vertexnum; i++)
            {
                index = i;
                min = short.maxvalue;

                for (int j = 1; j < graph.vertexnum; j++)
                {
                    //用于找出当前节点的邻接点中权值最小的未访问点
                    if (weight[j] < min && tempvertex[j] != 0)
                    {
                        min = weight[j];
                        index = j;
                    }
                }
                //累加权值
                sum += min;

                console.write("({0},{1})  ", tempvertex[index], graph.vertex[index]);

                //将取得的最小节点标识为已访问
                weight[index] = short.maxvalue;
                tempvertex[index] = 0;

                //从最新的节点出发,将此节点的weight比较赋值
                for (int j = 0; j < graph.vertexnum; j++)
                {
                    //已当前节点为出发点,重新选择最小边
                    if (graph.edges[index, j] < weight[j] && tempvertex[j] != used)
                    {
                        weight[j] = graph.edges[index, j];

                        //这里做的目的将较短的边覆盖点上一个节点的邻接点中的较长的边
                        tempvertex[j] = int.parse(graph.vertex[index]);
                    }
                }
            }
        }
        #endregion

 

二: 最短路径

1.   概念

        求最短路径问题其实也是非常有实用价值的,映射到交通系统图中,就是求两个城市间的最短路径问题,还是看这张图,我们可以很容易的看出比如

     v1到图中各顶点的最短路径。

      ① v1  ->  v2              直达,     权为2。

      ② v1  ->  v3              直达        权为3。

      ③ v1->v5->v4           中转       权为3+2=5。

      ④ v1  ->  v5               直达      权为3。

  算法系列15天速成——第十五天 图【下】(大结局)

2.  dijkstra算法

      我们的学习需要站在巨人的肩膀上,那么对于现实中非常复杂的问题,我们肯定不能用肉眼看出来,而是根据一定的算法推导出来的。

  dijkstra思想遵循 “走一步,看一步”的原则。

     第一步: 我们需要一个集合u,然后将v1放入u集合中,既然走了一步,我们就要看一步,就是比较一下v1的邻接点(v2,v3,v5),

                 发现(v1,v2)的权值最小,此时我们将v2放入u集合中,表示我们已经找到了v1到v2的最短路径。

     第二步:然后将v2做中间点,继续向前寻找权值最小的邻接点,发现只有v4可以连通,此时修改v4的权值为(v1,v2)+(v2,v4)=6。

                此时我们就要看一步,发现v1到(v3,v4,v5)中权值最小的是(v1,v5),此时将v5放入u集合中,表示我们已经找到了

                v1到v5的最短路径。

     第三步:然后将v5做中间点,继续向前寻找权值最小的邻接点,发现能连通的有v3,v4,当我们正想修该v3的权值时发现(v1,v3)的权值

                小于(v1->v5->v3),此时我们就不修改,将v3放入u集合中,最后我们找到了v1到v3的最短路径。

     第四步:因为v5还没有走完,所以继续用v5做中间点,此时只能连通(v5,v4),当要修改权值的时候,发现原来的v4权值为(v1,v2)+(v2,v4),而

                现在的权值为5,小于先前的6,此时更改原先的权值变为5,将v4放入集合中,最后我们找到了v1到v4的最短路径。

 

复制代码 代码如下:


#region dijkstra求出最短路径
        /// <summary>
/// dijkstra求出最短路径
/// </summary>
/// <param name="g"></param>
        public void dijkstra(matrixgraph g)
        {
            int[] weight = new int[g.vertexnum];

 

            int[] path = new int[g.vertexnum];

            int[] tempvertex = new int[g.vertexnum];

            console.writeline("\n请输入源点的编号:");

            //让用户输入要遍历的起始点
            int vertex = int.parse(console.readline()) - 1;

            for (int i = 0; i < g.vertexnum; i++)
            {
                //初始赋权值
                weight[i] = g.edges[vertex, i];

                if (weight[i] < short.maxvalue && weight[i] > 0)
                    path[i] = vertex;

                tempvertex[i] = 0;
            }

            tempvertex[vertex] = 1;
            weight[vertex] = 0;

            for (int i = 0; i < g.vertexnum; i++)
            {
                int min = short.maxvalue;

                int index = vertex;

                for (int j = 0; j < g.vertexnum; j++)
                {
                    //顶点的权值中找出最小的
                    if (tempvertex[j] == 0 && weight[j] < min)
                    {
                        min = weight[j];
                        index = j;
                    }
                }

                tempvertex[index] = 1;

                //以当前的index作为中间点,找出最小的权值
                for (int j = 0; j < g.vertexnum; j++)
                {
                    if (tempvertex[j] == 0 && weight[index] + g.edges[index, j] < weight[j])
                    {
                        weight[j] = weight[index] + g.edges[index, j];
                        path[j] = index;
                    }
                }
            }

            console.writeline("\n顶点{0}到各顶点的最短路径为:(终点 < 源点) " + g.vertex[vertex]);

            //最后输出
            for (int i = 0; i < g.vertexnum; i++)
            {
                if (tempvertex[i] == 1)
                {
                    var index = i;

                    while (index != vertex)
                    {
                        var j = index;
                        console.write("{0} < ", g.vertex[index]);
                        index = path[index];
                    }
                    console.writeline("{0}\n", g.vertex[index]);
                }
                else
                {
                    console.writeline("{0} <- {1}: 无路径\n", g.vertex[i], g.vertex[vertex]);
                }
            }
        }
        #endregion

 

最后上一下总的运行代码

 

复制代码 代码如下:


using system;
using system.collections.generic;
using system.linq;
using system.text;

 

namespace matrixgraph
{
    public class program
    {
        static void main(string[] args)
        {
            matrixgraphmanager manager = new matrixgraphmanager();

            //创建图
            matrixgraph graph = manager.creatematrixgraph();

            manager.outmatrix(graph);

            int sum = 0;

            manager.prim(graph, out sum);

            console.writeline("\n最小生成树的权值为:" + sum);

            manager.dijkstra(graph);

            //console.write("广度递归:\t");

//manager.bfstraverse(graph);

//console.write("\n深度递归:\t");

//manager.dfstraverse(graph);

            console.readline();

        }
    }

    #region 邻接矩阵的结构图
    /// <summary>
/// 邻接矩阵的结构图
/// </summary>
    public class matrixgraph
    {
        //保存顶点信息
        public string[] vertex;

        //保存边信息
        public int[,] edges;

        //深搜和广搜的遍历标志
        public bool[] istrav;

        //顶点数量
        public int vertexnum;

        //边数量
        public int edgenum;

        //图类型
        public int graphtype;

        /// <summary>
/// 存储容量的初始化
/// </summary>
/// <param name="vertexnum"></param>
/// <param name="edgenum"></param>
/// <param name="graphtype"></param>
        public matrixgraph(int vertexnum, int edgenum, int graphtype)
        {
            this.vertexnum = vertexnum;
            this.edgenum = edgenum;
            this.graphtype = graphtype;

            vertex = new string[vertexnum];
            edges = new int[vertexnum, vertexnum];
            istrav = new bool[vertexnum];
        }

    }
    #endregion

    /// <summary>
/// 图的操作类
/// </summary>
    public class matrixgraphmanager
    {
        #region 图的创建
        /// <summary>
/// 图的创建
/// </summary>
/// <param name="g"></param>
        public matrixgraph creatematrixgraph()
        {
            console.writeline("请输入创建图的顶点个数,边个数,是否为无向图(0,1来表示),已逗号隔开。");

            var initdata = console.readline().split(',').select(i => int.parse(i)).tolist();

            matrixgraph graph = new matrixgraph(initdata[0], initdata[1], initdata[2]);

            //我们默认“正无穷大为没有边”
            for (int i = 0; i < graph.vertexnum; i++)
            {
                for (int j = 0; j < graph.vertexnum; j++)
                {
                    graph.edges[i, j] = short.maxvalue;
                }
            }

            console.writeline("请输入各顶点信息:");

            for (int i = 0; i < graph.vertexnum; i++)
            {
                console.write("\n第" + (i + 1) + "个顶点为:");

                var single = console.readline();

                //顶点信息加入集合中
                graph.vertex[i] = single;
            }

            console.writeline("\n请输入构成两个顶点的边和权值,以逗号隔开。\n");

            for (int i = 0; i < graph.edgenum; i++)
            {
                console.write("第" + (i + 1) + "条边:\t");

                initdata = console.readline().split(',').select(j => int.parse(j)).tolist();

                int start = initdata[0];
                int end = initdata[1];
                int weight = initdata[2];

                //给矩阵指定坐标位置赋值
                graph.edges[start - 1, end - 1] = weight;

                //如果是无向图,则数据呈“二,四”象限对称
                if (graph.graphtype == 1)
                {
                    graph.edges[end - 1, start - 1] = weight;
                }
            }

            return graph;
        }
        #endregion

        #region 输出矩阵数据
        /// <summary>
/// 输出矩阵数据
/// </summary>
/// <param name="graph"></param>
        public void outmatrix(matrixgraph graph)
        {
            for (int i = 0; i < graph.vertexnum; i++)
            {
                for (int j = 0; j < graph.vertexnum; j++)
                {
                    if (graph.edges[i, j] == short.maxvalue)
                        console.write("∽\t");
                    else
                        console.write(graph.edges[i, j] + "\t");
                }
                //换行
                console.writeline();
            }
        }
        #endregion

        #region 广度优先
        /// <summary>
/// 广度优先
/// </summary>
/// <param name="graph"></param>
        public void bfstraverse(matrixgraph graph)
        {
            //访问标记默认初始化
            for (int i = 0; i < graph.vertexnum; i++)
            {
                graph.istrav[i] = false;
            }

            //遍历每个顶点
            for (int i = 0; i < graph.vertexnum; i++)
            {
                //广度遍历未访问过的顶点
                if (!graph.istrav[i])
                {
                    bfsm(ref graph, i);
                }
            }
        }

        /// <summary>
/// 广度遍历具体算法
/// </summary>
/// <param name="graph"></param>
        public void bfsm(ref matrixgraph graph, int vertex)
        {
            //这里就用系统的队列
            queue<int> queue = new queue<int>();

            //先把顶点入队
            queue.enqueue(vertex);

            //标记此顶点已经被访问
            graph.istrav[vertex] = true;

            //输出顶点
            console.write(" ->" + graph.vertex[vertex]);

            //广度遍历顶点的邻接点
            while (queue.count != 0)
            {
                var temp = queue.dequeue();

                //遍历矩阵的横坐标
                for (int i = 0; i < graph.vertexnum; i++)
                {
                    if (!graph.istrav[i] && graph.edges[temp, i] != 0)
                    {
                        graph.istrav[i] = true;

                        queue.enqueue(i);

                        //输出未被访问的顶点
                        console.write(" ->" + graph.vertex[i]);
                    }
                }
            }
        }
        #endregion

        #region 深度优先
        /// <summary>
/// 深度优先
/// </summary>
/// <param name="graph"></param>
        public void dfstraverse(matrixgraph graph)
        {
            //访问标记默认初始化
            for (int i = 0; i < graph.vertexnum; i++)
            {
                graph.istrav[i] = false;
            }

            //遍历每个顶点
            for (int i = 0; i < graph.vertexnum; i++)
            {
                //广度遍历未访问过的顶点
                if (!graph.istrav[i])
                {
                    dfsm(ref graph, i);
                }
            }
        }

        #region 深度递归的具体算法
        /// <summary>
/// 深度递归的具体算法
/// </summary>
/// <param name="graph"></param>
/// <param name="vertex"></param>
        public void dfsm(ref matrixgraph graph, int vertex)
        {
            console.write("->" + graph.vertex[vertex]);

            //标记为已访问
            graph.istrav[vertex] = true;

            //要遍历的六个点
            for (int i = 0; i < graph.vertexnum; i++)
            {
                if (graph.istrav[i] == false && graph.edges[vertex, i] != 0)
                {
                    //深度递归
                    dfsm(ref graph, i);
                }
            }
        }
        #endregion
        #endregion

        #region prim算法获取最小生成树
        /// <summary>
/// prim算法获取最小生成树
/// </summary>
/// <param name="graph"></param>
        public void prim(matrixgraph graph, out int sum)
        {
            //已访问过的标志
            int used = 0;

            //非邻接顶点标志
            int noadj = -1;

            //定义一个输出总权值的变量
            sum = 0;

            //临时数组,用于保存邻接点的权值
            int[] weight = new int[graph.vertexnum];

            //临时数组,用于保存顶点信息
            int[] tempvertex = new int[graph.vertexnum];

            //取出邻接矩阵的第一行数据,也就是取出第一个顶点并将权和边信息保存于临时数据中
            for (int i = 1; i < graph.vertexnum; i++)
            {
                //保存于邻接点之间的权值
                weight[i] = graph.edges[0, i];

                //等于0则说明v1与该邻接点没有边
                if (weight[i] == short.maxvalue)
                    tempvertex[i] = noadj;
                else
                    tempvertex[i] = int.parse(graph.vertex[0]);
            }

            //从集合v中取出v1节点,只需要将此节点设置为已访问过,weight为0集合
            var index = tempvertex[0] = used;
            var min = weight[0] = short.maxvalue;

            //在v的邻接点中找权值最小的节点
            for (int i = 1; i < graph.vertexnum; i++)
            {
                index = i;
                min = short.maxvalue;

                for (int j = 1; j < graph.vertexnum; j++)
                {
                    //用于找出当前节点的邻接点中权值最小的未访问点
                    if (weight[j] < min && tempvertex[j] != 0)
                    {
                        min = weight[j];
                        index = j;
                    }
                }
                //累加权值
                sum += min;

                console.write("({0},{1})  ", tempvertex[index], graph.vertex[index]);

                //将取得的最小节点标识为已访问
                weight[index] = short.maxvalue;
                tempvertex[index] = 0;

                //从最新的节点出发,将此节点的weight比较赋值
                for (int j = 0; j < graph.vertexnum; j++)
                {
                    //已当前节点为出发点,重新选择最小边
                    if (graph.edges[index, j] < weight[j] && tempvertex[j] != used)
                    {
                        weight[j] = graph.edges[index, j];

                        //这里做的目的将较短的边覆盖点上一个节点的邻接点中的较长的边
                        tempvertex[j] = int.parse(graph.vertex[index]);
                    }
                }
            }
        }
        #endregion

        #region dijkstra求出最短路径
        /// <summary>
/// dijkstra求出最短路径
/// </summary>
/// <param name="g"></param>
        public void dijkstra(matrixgraph g)
        {
            int[] weight = new int[g.vertexnum];

            int[] path = new int[g.vertexnum];

            int[] tempvertex = new int[g.vertexnum];

            console.writeline("\n请输入源点的编号:");

            //让用户输入要遍历的起始点
            int vertex = int.parse(console.readline()) - 1;

            for (int i = 0; i < g.vertexnum; i++)
            {
                //初始赋权值
                weight[i] = g.edges[vertex, i];

                if (weight[i] < short.maxvalue && weight[i] > 0)
                    path[i] = vertex;

                tempvertex[i] = 0;
            }

            tempvertex[vertex] = 1;
            weight[vertex] = 0;

            for (int i = 0; i < g.vertexnum; i++)
            {
                int min = short.maxvalue;

                int index = vertex;

                for (int j = 0; j < g.vertexnum; j++)
                {
                    //顶点的权值中找出最小的
                    if (tempvertex[j] == 0 && weight[j] < min)
                    {
                        min = weight[j];
                        index = j;
                    }
                }

                tempvertex[index] = 1;

                //以当前的index作为中间点,找出最小的权值
                for (int j = 0; j < g.vertexnum; j++)
                {
                    if (tempvertex[j] == 0 && weight[index] + g.edges[index, j] < weight[j])
                    {
                        weight[j] = weight[index] + g.edges[index, j];
                        path[j] = index;
                    }
                }
            }

            console.writeline("\n顶点{0}到各顶点的最短路径为:(终点 < 源点) " + g.vertex[vertex]);

            //最后输出
            for (int i = 0; i < g.vertexnum; i++)
            {
                if (tempvertex[i] == 1)
                {
                    var index = i;

                    while (index != vertex)
                    {
                        var j = index;
                        console.write("{0} < ", g.vertex[index]);
                        index = path[index];
                    }
                    console.writeline("{0}\n", g.vertex[index]);
                }
                else
                {
                    console.writeline("{0} <- {1}: 无路径\n", g.vertex[i], g.vertex[vertex]);
                }
            }
        }
        #endregion
    }
}

 

算法系列15天速成——第十五天 图【下】(大结局)

 

算法速成系列至此就全部结束了,公司给我们的算法培训也于上周五结束,呵呵,赶一下同步。最后希望大家能对算法重视起来,

学好算法,终身收益。