C源码ArcEngine最短路径分析
C语言迪杰斯特拉实现最短路径算法
C语言迪杰斯特拉实现最短路径算法迪杰斯特拉(Dijkstra)算法是一种用于在加权图中寻找从起点到终点的最短路径的算法。
它使用贪心算法的原理,每次选择权重最小的边进行扩展,直到找到终点或者无法扩展为止。
下面是C语言中迪杰斯特拉算法的实现。
```c#include <stdio.h>#include <stdbool.h>//定义图的最大节点数#define MAX_NODES 100//定义无穷大的距离#define INFINITY 9999//自定义图的结构体typedef structint distance[MAX_NODES][MAX_NODES]; // 节点间的距离int numNodes; // 节点数} Graph;//初始化图void initGraph(Graph* graph)int i, j;//设置所有节点之间的初始距离为无穷大for (i = 0; i < MAX_NODES; i++)for (j = 0; j < MAX_NODES; j++)graph->distance[i][j] = INFINITY;}}graph->numNodes = 0;//添加边到图void addEdge(Graph* graph, int source, int destination, int weight)graph->distance[source][destination] = weight;//打印最短路径void printShortestPath(int* parent, int node)if (parent[node] == -1)printf("%d ", node);return;}printShortestPath(parent, parent[node]);printf("%d ", node);//执行迪杰斯特拉算法void dijkstra(Graph* graph, int source, int destination) int i, j;//存储起点到各个节点的最短距离int dist[MAX_NODES];//存储当前节点的父节点int parent[MAX_NODES];//存储已访问的节点bool visited[MAX_NODES];//初始化所有节点的距离和父节点for (i = 0; i < graph->numNodes; i++)dist[i] = INFINITY;parent[i] = -1;visited[i] = false;}//设置起点的距离为0dist[source] = 0;//寻找最短路径for (i = 0; i < graph->numNodes - 1; i++)int minDist = INFINITY;int minNode = -1;//选择距离最小的节点作为当前节点for (j = 0; j < graph->numNodes; j++)if (!visited[j] && dist[j] < minDist)minDist = dist[j];minNode = j;}}//标记当前节点为已访问visited[minNode] = true;//更新最短距离和父节点for (j = 0; j < graph->numNodes; j++)if (!visited[j] && (dist[minNode] + graph->distance[minNode][j]) < dist[j])dist[j] = dist[minNode] + graph->distance[minNode][j];parent[j] = minNode;}}}//打印最短路径及距离printf("Shortest Path: ");printShortestPath(parent, destination);printf("\nShortest Distance: %d\n", dist[destination]); int maiGraph graph;int numNodes, numEdges, source, destination, weight;int i;//初始化图initGraph(&graph);//输入节点数和边数printf("Enter the number of nodes: ");scanf("%d", &numNodes);printf("Enter the number of edges: ");scanf("%d", &numEdges);graph.numNodes = numNodes;//输入边的信息for (i = 0; i < numEdges; i++)printf("Enter source, destination, and weight for edge %d: ", i + 1);scanf("%d %d %d", &source, &destination, &weight);addEdge(&graph, source, destination, weight);}//输入起点和终点printf("Enter the source node: ");scanf("%d", &source);printf("Enter the destination node: ");scanf("%d", &destination);//执行迪杰斯特拉算法dijkstra(&graph, source, destination);return 0;```上述代码中,我们首先定义了一个图的结构体,里面包括节点间的距离矩阵和节点数。
C语言迪杰斯特拉实现最短路径算法
数据结构课程设计报告----旅游咨询系统设计目录一、需求分析二、系统分析三、概要设计一、系统划分二、邻接矩阵建立流程图:三、迪杰斯特拉算法流图四、详细设计五、调试分析一、运行结果二、改进设想六、课设总结旅游咨询系统设计一、需求分析在交通网络日益发达的今天,人们出行有很多种方式、路线,而如何选择符合需要的方式路线成为大家的一大难题。
所以,在此我利用计算机建立一个旅游咨询系统。
在系统中采用图来构造各个城市之间的联系,图中顶点表示城市,边表示各个城市之间的路线,所带权值为两个城市间的路程、时间或车费等。
这个交通咨询系统可以回答旅客提出的各种问题,例如:如何选择一条路径使得从A城到B城里程最短;如何选择一条路径使得从A城到B城花费最低;如何选择一条路径使得从A 城到B城所用的时间最少等等的一系列问题。
二、系统分析设计一个旅游咨询系统,能咨询从任何一个城市顶点到其他城市顶点之间的最短路径(里程、最低花费或是最少时间等问题。
对于不同的咨询要求,可输入城市间的路程、所需时间或是所需费用等信息。
旅客可以在同一个系统中综合考虑自己的各目标城市,选择一个最佳的旅游路线和出行方式。
针对最短路径问题,在本系统中采用图的相关知识,采用了迪杰斯特拉算法,解决在实际情况中的最短路径问题,而迪杰斯特拉算法的时间复杂度为O(n2,空间复杂度为O(n。
本系统使用邻接矩阵存储无向图。
其中,建立矩阵的时间复杂度为O(n2,但是利用其查找一条边的时间复杂度为O(1。
本系统中包括了利用邻接矩阵建立图的存储结构和单源最短问题两大部分,使用指针数组实现利用一个程序实现最短路径和最短时间的运算。
并且本系统设置了人性化的系统提示菜单,方便使用者的使用。
三、概要设计一、系统划分该系统可以划分为三个部分:1、利用邻接矩阵建立图的存储结构;2、利用迪杰斯特拉算法解决单源最短路径问题;3、实现城市之间的最短路径问题和最短时间问题。
二、邻接矩阵建立流程图:四、详细设计本课程设计的源程序如下所示:#include#include#define MVNum 100#define Maxint 9999 /*将无穷大的数值设为9999*/ typedef char vertextype;/*建立无向图*/typedef int adjmatrix;typedef struct{vertextype vexs[MVNum];adjmatrix arcs[MVNum][MVNum];}mgraph;mgraph *G[2]; /*设置指针数组用以实现距离和时间最小值求取*/void city_number( /*输出城市代表序号*/{ printf("************************************************************************ *\n";printf(" 1、北京 2、上海 3、香港 4、天津 5、重庆 6、澳门 7、哈尔滨 8、石家庄";printf(" \n 9、兰州 10、昆明 11、成都 12、长春 13、沈阳 14、长沙 15、海口 16、西安";printf("\n************************************************************************ *\n";}void Createmgraph(int a,int n,int e /*建立无向邻接矩阵*/{int i,j,k;int w;for(i=1;i<=n;i++for(j=1;j<=n;j++if(i==j G[a]->arcs[i][j]=0; /*邻接矩阵对角线初始值设为0*/else G[a]->arcs[i][j]=Maxint; /*其他元素设为无穷大*/for(k=1;k<=e;k++ /*读入e条边数的信息*/{printf("\n输入图中各起点终点及其权值i,j,w:"; /*读入无向边及其权值*/scanf("%d,%d,%d",&i,&j,&w;G[a]->arcs[i][j]=w;G[a]->arcs[j][i]=w;}}void Dijkstra(int a,int v0,int N/*Dijkstra算法的实现和打印*/{enum boolean S[MVNum];/*终点集合*/int dist[MVNum],path[MVNum];/*dist表示源点v0到图中其余顶点的最短长度,path表示其对应的路径*/int i,wmin,u,num=1,k;for(i=1;i<=N;i++ /*数组dist和集合S付初值*/{dist[i]=G[a]->arcs[v0][i]; /*数组dist初值为邻接矩阵*/S[i]=0; /*集合S初值设为空集*/if(dist[i]else path[i]=0;}S[v0]=1; /*源点v0放入集合S中*/path[v0]=0;do{wmin=Maxint; /*wmin最小值设为无穷大*/u=v0;for(i=1;i<=N;i++if(S[i]==0 /*选择不在S中且距离最小的顶点u*/if((dist[i]{u=i;wmin=dist[i];}S[u]=1; /*把距离最小的顶点u放入集合S中*/for(i=1;i<=N;i++ /*修改不在S中的顶点距离*/if(S[i]==0if(dist[u]+G[a]->arcs[u][i]{dist[i]=dist[u]+G[a]->arcs[u][i];path[i]=u;}num++;}while(num<=N;printf("\n\t输出带权无向图的单元最短路径为:\n\t";/*打印v0到其他顶点的最短路径*/ for(i=1;i<=N;i++{if(S[i]==1{k=i;printf("\n\t顶点%d到%d之间的路径为:",v0,i;while(k!=v0{printf("%d<--",k; /*输出后继顶点*/k=path[k]; /*继续寻找下一个后继顶点*/}printf("%d",k; /*输出终点*/printf(",最短路径长度为%d\n",dist[i]; /*输出最短路径*/}else printf("\n\t顶点%d到%d之间没有路径!",v0,i;}printf("\n\t求一个城市到所有城市的最短路径结束,谢谢!\n\n\t\t";}void main( /*旅游咨询系统*/{int n,e,v,u,i,x;int z=0;G[1]=(mgraph *malloc(sizeof(mgraph; /*建立类型为mgraph的十字链表结构*/G[2]=(mgraph *malloc(sizeof(mgraph;printf("****************欢迎使用旅游咨询系统****************\n";printf("输入图中顶点个数和边数n,e:";scanf("%d,%d",&n,&e;city_number(;for(i=1;i<=n;i++ /*输入顶点信息*/{printf("\n请输入图的所有顶点i=";scanf("%d",&x;G[1]->vexs[i]=x; /*将顶点信息输入一维数组中*/G[2]->vexs[i]=x;}printf("\n请输入距离矩阵的数值\n";Createmgraph(1,n,e; /*建立距离矩阵*/ printf("\n距离矩阵建立完毕\n请输入时间矩阵的数值";Createmgraph(2,n,e; /*建立时间矩阵*/printf("\n无向图的存储结构建立完毕!\n";do{printf("\n\n\n************进行最短查询************\n";printf("=========================================\n";printf("1.求一个城市到所有城市的最短路径\n";printf("2.求一个城市到所有城市的最短时间\n";printf("3.退出\n";printf("=========================================\n";printf("请输入选择:";scanf("%d",&z; /*输入选择选择矩阵*/city_number(;if(z==1{printf("\n选择1 求一个城市到所有城市的最短路径\n";printf("求单源路径,输入源点v :"; /*输入源点v0*/scanf("%d",&v;Dijkstra(1,v,n; /*计算最短距离*/}else if(z==2{printf("\n选择2 求一个城市到所有城市的最短时间\n"; printf("求单源路径,输入源点,u :";scanf("%d",&u;Dijkstra(2,u,n; /*计算最短时间*/}else if(z==3printf("\n结束查询!谢谢使用!!\n";else printf("输入错误!!\n"; /*输入不为1-3则重新选择*/ }while(z!=3; /*输入3则退出*/printf("谢谢您的使用,再见!!!!\n";}五、调试分析一、运行结果1、输入顶点总数为6,边的总数为10,并输入顶点信息。
arcmap 最短路径计算
arcmap 最短路径计算ArcMap是地理信息系统(GIS)中最常用的软件之一,它提供了一整套丰富的地图制图、空间分析和数据管理等工具,而其中最独特和实用的功能之一就是最短路径分析。
本文将介绍ArcMap最短路径计算的相关知识和应用。
1. 最短路径定义在ArcMap中,最短路径指的是从一个地理位置到另一个地理位置的最短距离或最短路线,即使在大地曲率和地形起伏复杂的情况下,也可以计算出其中的最优路径。
最短路径计算主要用于寻路、行车导航、道路规划等领域,可以快速计算出从起点到终点的最优路径,帮助用户减少时间、成本和资源浪费。
2. 最短路径计算方法在ArcMap中,最短路径计算方法有两种:基于网络数据集(Network Dataset)的最短路径计算和基于地表数据的最短路径计算。
2.1 基于网络数据集的最短路径计算网络数据集是ArcMap中用于路网和路径分析的一个重要概念,它可以将地图上的道路网络和交通设施等要素构建成一个典型的网络结构,方便进行最短路径计算。
基于网络数据集的最短路径计算是通过网络分析工具实现的,其中包括了三种方法:(1)朴素最短路径:该方法是一种基于Dijkstra算法的最短路径计算,通过计算道路网格之间的距离和速度等信息,计算最短路径。
(2)全局最短路径:该方法是一种基于Floyd算法的最短路径计算,能够考虑道路网格的交叉和环路,计算出整个网络中的最短路径。
(3)受限最短路径:该方法是一种根据用户设定的条件进行路径规划的最短路径计算,例如最小出行时间、最小距离和最少节点等。
基于网络数据集的最短路径计算具有准确、快速和灵活等优点,适合于处理中大型的道路网络和公共交通系统等。
2.2 基于地表数据的最短路径计算基于地表数据的最短路径计算适用于区域较小、地形复杂等情况下的跨越,由于这类分析通常基于高程数据计算,因此也被称为高程路径分析。
它通过三维分析工具实现,包括了以下方法:(1)距离分析:该方法根据地形高程信息计算最短路径,可以计算起点和终点之间的直线距离、欧几里得距离和沿地形走的最短距离等。
求最短路径_C语言程序
中国地质大学(武汉)数据结构课程设计报告****: ***班级序号:学号:姓名:实习二求最短路径一.问题描述试设计一个算法,求图中一个源点到其他各顶点的最短路径。
二.基本要求(1)用邻接表表示图;(2)按长度非递减次序打印输出最短路径的长度及相应路径。
三.测试数据四.用到的数据结构和函数(1)定义数组typedef char VertexType;typedef int Adjmatrix;typedef struct{VertexType vexs[MVNum]; //顶点数组,类型假定为char型Adjmatrix arcs[MVNum][MVNum]; //邻接矩阵,类型假定为int型}MGraph;(2)迪杰斯特拉算法void Dijkstra(MGraph *G,int v1,int n){ //用迪杰斯特拉算法求有向图G的v1顶点到其他顶点v的最短路径P[v]和其权D[v] //设G是有向图的邻接矩阵,若边<i,j>不存在,则G[i][j]=Maxint//S[v]为真当且仅当v在S中int D2[MVNum],P2[MVNum];int v,i,w,min;enum boolean S[MVNum];for(v=1;v<=n;v++){//初始化S和DS[v]=FALSE; //设置最短路径终点集D2[v]=G->arcs[v1][v]; //设置初始的最短路径值if(D2[v]<Maxint)P2[v]=v1; //v1是v的前驱elseP2[v]=0; //v无前驱}D2[v1]=0;S[v1]=TURE; //S集初始时只有源点,源点到其自身的距离为0//开始循环,每次求得v1到某个v顶点的最短路径,并加v到S集中for(i=2;i<n;i++){min=Maxint;for(w=1;w<=n;w++)if(!S[w]&&D2[w]<min){ //w顶点离v1顶点更近v=w;min=D2[w];}S[v]=TURE;for(w=1;w<=n;w++) //更新当前最短路径及距离if(!S[w]&&(D2[v]+G->arcs[v][w]<D2[w])){ //修改D2[w]和P2[w]D2[w]=D2[v]+G->arcs[v][w];P2[w]=v;}}printf("路径长度路径\n");for(i=1;i<=n;i++){printf("%5d",D2[i]);printf("%5d",i);v=P2[i];while(v!=0){printf("<-%d",v);v=P2[v];}printf("\n");}}(3)费洛伊德算法void Floyd(MGraph *G,int n){int i,j,k,v,w;for(i=1;i<=n;i++) //设置路径长度D和路径path初值for(j=1;j<=n;j++){if(G->arcs[i][j]!=Maxint)P[i][j]=j; //j是i的后继elseP[i][j]=0;D[i][j]=G->arcs[i][j];}for(k=1;k<=n;k++){ //做k次迭代,每次均试图将顶点k扩充到当前求得的从i到j的最短路径P[i][j]上for(i=1;i<=n;i++)for(j=1;j<=n;j++){if(D[i][k]+D[k][j]<D[i][j]){D[i][j]=D[i][k]+D[k][j]; //修改长度P[i][j]=P[i][k];printf("dij=%d,pij=%d\n",D[i][j],P[i][j]);}}}}六.源代码#include"stdio.h"#include"stdlib.h"#define MVNum 100 //最大顶点数#define Maxint 32767enum boolean{ FALSE,TURE };typedef char VertexType;typedef int Adjmatrix;typedef struct{VertexType vexs[MVNum]; //顶点数组,类型假定为char型Adjmatrix arcs[MVNum][MVNum]; //邻接矩阵,类型假定为int型}MGraph;int D1[MVNum],P1[MVNum];int D[MVNum][MVNum],P[MVNum][MVNum];/*建立有向图的存储结构*/void CreateMGraph(MGraph *G,int n,int e){ //采用邻接矩阵表示法构造有向图G,n和e表示图的顶点数和边数int i,j,k,w;for(i=1;i<=n;i++)G->vexs[i]=(char)i;for(i=1;i<=n;i++)for(j=1;j<=n;j++)G->arcs[i][j]=Maxint; //初始化邻接矩阵printf("输入%d条边的i,j及w:\n",e);for(k=1;k<=e;k++){ //读入e条边,建立邻接矩阵scanf("%d,%d,%d",&i,&j,&w);G->arcs[i][j]=w;}printf("有向图的存储结构建立完成。
使用VC++开发基于ArcEngine的三维管线距离分析组件
使用VC++开发基于ArcEngine的三维管线距离分析组件蒋许锋王刚于海波天津市测绘院摘要:采用GIS管理管线有着非常重要的意义。
三维管线的距离分析与空间关系的展示,无论对于管线规划、管线检测还是为其他工程提供管线资料都非常重要。
ArcGIS作为行业应用最广泛的GIS软件平台,但是三维管线之间的距离分析并没有提供解决方法,本文同过分析三维管线的特点,结合行业的业务需求,采用VC++结合相关技术,完成三维管线的距离分析与展示,最终实现可以插入到ArcGIS中的组件。
Abstract:Using GIS technology to manage pipeline is very significant for the society. To calculate the distance between two pipeline and display the 3D modal of the pipelines are very important. ArcGIS dosen’t give an advice to get the distance though it can display them. This paper Implemented a COM using VC++ and ATL based on ICommand and Itool of ArcEngine to solve this problem.关键字三维管线 ArcEngine COM组件 ATL STL一引言无论城市还是农村,地上地下都分布着各种诸于电力、给排水、燃气、通信、有线电视等等各种管线。
计算机技术的发展尤其是GIS技术的发展,使得这些管线的管理,由传统的MIS加图纸的方法,逐渐向充分利用计算机视觉表达,更加直观查看、深入分析的管理模式。
管线管理中,两根管线之间的距离分析非常重要。
不同性质、用途、材质的管线,对它们之间的空间距离有着严格的要求。
迪杰斯特拉算法c语言从某个源点到其余各顶点的最短路径 -回复
迪杰斯特拉算法c语言从某个源点到其余各顶点的最短路径-回复迪杰斯特拉算法(Dijkstra's algorithm)是求解图中从某个源点到其余各顶点的最短路径的经典算法。
本文将通过一步一步的回答,详细解释迪杰斯特拉算法在C语言中的具体实现。
文章将包括算法原理、伪代码、关键函数实现以及一个简单的示例。
一、算法原理迪杰斯特拉算法是一种贪心算法,它通过逐步扩展最短路径的方式来找到源点到其他顶点的最短路径。
具体的步骤如下:1. 创建一个空的距离表,用于记录源点到各个顶点的最短路径,初始时将源点到自身的距离设置为0,其他顶点的距离设置为无穷大。
2. 选择一个距离表中距离最小的顶点,标记该顶点为已访问。
3. 对于已访问的顶点,更新其相邻顶点的距离,如果通过当前顶点的距离比原距离小,则更新距离值。
4. 重复步骤2和步骤3,直到所有顶点都被访问过或者没有可达的顶点。
二、伪代码为了更好地理解算法的实现,下面是使用伪代码描述的迪杰斯特拉算法:1. 创建一个距离表,用于记录源点到各个顶点的最短路径距离。
2. 将源点到自身的距离设置为0,其他顶点的距离设置为无穷大。
3. 创建一个标记表,用于标记已访问的顶点。
4. 创建一个优先队列(最小堆),用于选择下一个要访问的顶点。
5. 将源点入队列。
6. 当队列不为空时,执行以下操作:6.1. 选择队列中距离最小的顶点,将其出队。
6.2. 如果该顶点已经被访问过,则跳过该顶点。
6.3. 标记该顶点为已访问。
6.4. 对于该顶点的所有邻接顶点,计算通过当前顶点到达邻接顶点的距离,如果距离比原来的距离小,则更新距离表中的值。
6.5. 对于未访问过的邻接顶点,将其入队列。
7. 输出距离表中源点到各个顶点的最短路径距离。
三、关键函数实现下面是使用C语言实现迪杰斯特拉算法的关键函数。
c用于记录源点到各个顶点的最短路径距离int distance[MAX_VERTICES];用于标记已访问的顶点bool visited[MAX_VERTICES];void Dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int source) {初始化距离表和标记表for (int i = 0; i < MAX_VERTICES; i++) {distance[i] = INT_MAX;visited[i] = false;}将源点到自身的距离设置为0distance[source] = 0;循环遍历每个顶点for (int count = 0; count < MAX_VERTICES; count++) {int u = -1; 用于记录下一个要访问的顶点int minDistance = INT_MAX;选择距离最小的未访问顶点作为下一个要访问的顶点for (int i = 0; i < MAX_VERTICES; i++) {if (!visited[i] && distance[i] < minDistance) {minDistance = distance[i];u = i;}}if (u == -1) {没有可达的顶点break;}visited[u] = true; 标记该顶点为已访问更新通过顶点u到达其他邻接顶点的距离for (int v = 0; v < MAX_VERTICES; v++) {if (!visited[v] && graph[u][v] != INT_MAX && distance[u] + graph[u][v] < distance[v]) {distance[v] = distance[u] + graph[u][v];}}}}四、示例为了演示迪杰斯特拉算法的使用,我们使用以下图结构作为示例:int graph[MAX_VERTICES][MAX_VERTICES] = {{0, 4, 2, INT_MAX, INT_MAX},{INT_MAX, 0, 1, 5, INT_MAX},{INT_MAX, INT_MAX, 0, INT_MAX, 3},{INT_MAX, INT_MAX, INT_MAX, 0, 1},{INT_MAX, INT_MAX, INT_MAX, INT_MAX, 0}};int source = 0;Dijkstra(graph, source);上述图结构表示一个有5个顶点的有向带权图,带权值表示了从一个顶点到另一个顶点的距离。
Arcgis操作 实验十五:最短路径分析
实验十五:最短路径分析一、实验目的1、掌握各种类型的最短路径分析;2、理解网络分析原理。
二、实验准备数据准备:City.mdb软件准备:ArcGIS Desktop9.x,ArcCatalog三、实验内容根据不同的要求,获得到达指定目的地的最佳路径,并给出路径的长度;找出距景点最近的某设施的路径。
1、在网络中指定一个商业中心,分别求出在不同距离、时间的限制下从家到商业中心的最佳路径;2、给定访问顺序,按要求找出从家出发,逐个经过访问点,最终到达目的地的最佳路径;3、研究阻强的设置对最佳路径选择的影响。
四、实验步骤启动ArcMap ,打开city. mdb ,双击city数据库,加载数据。
对点状要素place符号化:以HOME字段,1值为家,0值为商业中心。
具体步骤见操作视频:最短路径分析.exe图1 无权重参照的最短路径显示(1)无权重最佳路径的生成1)在网络分析工具条上,选择旗标工具,将旗标放在“家”和想要取得“商业中心”点上。
2)选择Analysis/Options命令,打开Analysis Options对话框,确认Weights和Weight Filter 标签项全部是None,这种情况下进行的最短路径分析是完全按照这个网络自身的长短来确定。
3)在Track Task文本框中选择Find path。
单击solve按钮。
显示最短路径(图1),这条路径的总成本显示在状态栏中。
(2)加权最佳路径生成1)在设施网络分析工具条下,点选旗标工具,将旗标分别放在“家”和想去的某个“商业中心”的位置上。
2)选择Analysis/Options命令,打开Analysis Options对话框(图2)进入Weights标签页,在边的权重上,全部选择长度权重属性。
图2 长度权重属性设置3)在Track Task文本枢中选择Find path,单击solve按钮,则以长度为比重的最短路径将显示出来(图3),这条路径的总成本显示在状态栏中。
C语言算法最短路径最小生成树和拓扑排序
C语言算法最短路径最小生成树和拓扑排序C语言算法:最短路径、最小生成树与拓扑排序编程领域涵盖了众多算法和数据结构,并且在实际应用中起到了至关重要的作用。
本文将重点探讨C语言中的三种经典算法:最短路径算法、最小生成树算法以及拓扑排序算法。
通过学习这些算法,可以帮助我们更好地解决实际问题。
一、最短路径算法最短路径算法主要用于在带有权重的有向或无向图中寻找两个节点之间的最短路径。
常用的最短路径算法有迪杰斯特拉算法(Dijkstra)和弗洛伊德-沃尔什算法(Floyd-Warshall)。
下面我们将重点介绍Dijkstra算法。
Dijkstra算法基于贪心策略,通过逐步确定从起点到各个节点的最短距离来找出最短路径。
它适用于没有负权边的图,时间复杂度为O(V^2),其中V表示节点数目。
1. 算法思路:- 创建一个存储最短路径的数组dist[],初始化为无穷大(代表无法达到),起点dist[起点]设为0。
- 创建一个存储已访问节点的数组visited[],初始化为false。
- 从起点开始,依次遍历与起点相邻的节点,更新最短路径距离。
- 选取距离起点最近的节点作为下一个访问节点,并更新最短路径数组。
- 重复上述步骤,直到遍历完所有节点。
- 最终得到起点到每个节点的最短路径。
2. 示例代码:```c// 使用邻接矩阵存储图#define MAX_SIZE 100#define INF 0x3f3f3f3fvoid dijkstra(int graph[MAX_SIZE][MAX_SIZE], int start, int n) {int dist[MAX_SIZE]; // 存储最短路径bool visited[MAX_SIZE]; // 标记已访问节点// 初始化for (int i = 0; i < n; i++) {dist[i] = INF;visited[i] = false;}dist[start] = 0;// 寻找最短路径for (int count = 0; count < n - 1; count++) {int minDist = INF;int u;// 选取距离起点最近的节点for (int v = 0; v < n; v++) {if (!visited[v] && dist[v] <= minDist) {minDist = dist[v];u = v;}}visited[u] = true;// 更新最短路径for (int v = 0; v < n; v++) {if (!visited[v] && graph[u][v] && dist[u] != INF && dist[u] + graph[u][v] < dist[v]) {dist[v] = dist[u] + graph[u][v];}}}// 输出最短路径for (int i = 0; i < n; i++) {printf("起点到节点 %d 的最短距离为:%d\n", i, dist[i]);}}```二、最小生成树算法最小生成树(Minimum Spanning Tree,简称MST)是一种在连通图中生成所有节点的树,且树的边权重之和最小的子图。
ArcEngine+最短路径分析(C#源码)
using workAnalysis;public class ClsPathFinder{private IGeometricNetwork m_ipGeometricNetwork;private IMap m_ipMap;private IPointCollection m_ipPoints;private IPointToEID m_ipPointToEID;private double m_dblPathCost =0;private IEnumNetEID m_ipEnumNetEID_Junctions;private IEnumNetEID m_ipEnumNetEID_Edges;private IPolyline m_ipPolyline;#region Public Function//返回和设置当前地图public IMap SetOrGetMap{set{ m_ipMap = value;}get{return m_ipMap;}}//打开网络public void OpenFeatureDatasetNetwork(IFeatureDataset FeatureDataset){CloseWorkspace();if (!InitializeNetworkAndMap(FeatureDataset))Console.WriteLine( "打开出错");}//输入点的集合public IPointCollection StopPoints{set{m_ipPoints= value;}get{return m_ipPoints;}}//路径成本public double PathCost{get {return m_dblPathCost;}}//返回路径public IPolyline PathPolyLine(){IEIDInfo ipEIDInfo;IGeometry ipGeometry;if(m_ipPolyline!=null)return m_ipPolyline;m_ipPolyline = new PolylineClass();IGeometryCollection ipNewGeometryColl = m_ipPolyline as IGeometryCollection;ISpatialReference ipSpatialReference = m_ipMap.SpatialReference; IEIDHelper ipEIDHelper = new EIDHelperClass();ipEIDHelper.GeometricNetwork = m_ipGeometricNetwork;ipEIDHelper.OutputSpatialReference = ipSpatialReference;ipEIDHelper.ReturnGeometries = true;IEnumEIDInfo ipEnumEIDInfo =ipEIDHelper.CreateEnumEIDInfo(m_ipEnumNetEID_Edges);int count = ipEnumEIDInfo.Count;ipEnumEIDInfo.Reset();for(int i =0;i<count;i++){ipEIDInfo = ipEnumEIDInfo.Next();ipGeometry = ipEIDInfo.Geometry;ipNewGeometryColl.AddGeometryCollection( ipGeometry as IGeometryCollection);}return m_ipPolyline;}//解决路径public void SolvePath(string WeightName){try{int intEdgeUserClassID;int intEdgeUserID;int intEdgeUserSubID;int intEdgeID;IPoint ipFoundEdgePoint;double dblEdgePercent;/*C#中使用*ITraceFlowSolverGEN替代ITraceFlowSolver*/ITraceFlowSolverGEN ipTraceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN;INetSolver ipNetSolver = ipTraceFlowSolver as INetSolver;INetwork ipNetwork = m_work;ipNetSolver.SourceNetwork = ipNetwork;INetElements ipNetElements = ipNetwork as INetElements;int intCount = m_ipPoints.PointCount;//定义一个边线旗数组IEdgeFlag[] pEdgeFlagList = new EdgeFlagClass[intCount];for(int i = 0;i<intCount ;i++){INetFlag ipNetFlag = new EdgeFlagClass()as INetFlag;IPoint ipEdgePoint = m_ipPoints.get_Point(i);//查找输入点的最近的边线m_ipPointToEID.GetNearestEdge(ipEdgePoint, out intEdgeID,out ipFoundEdgePoint, out dblEdgePercent);ipNetElements.QueryIDs( intEdgeID, esriElementType.esriETEdge, out intEdgeUserClassID, out intEdgeUserID,out intEdgeUserSubID);erClassID = intEdgeUserClassID;erID = intEdgeUserID;erSubID = intEdgeUserSubID;IEdgeFlag pTemp = (IEdgeFlag)(ipNetFlag as IEdgeFlag);pEdgeFlagList=pTemp;}ipTraceFlowSolver.PutEdgeOrigins(ref pEdgeFlagList);INetSchema ipNetSchema = ipNetwork as INetSchema;INetWeight ipNetWeight =ipNetSchema.get_WeightByName(WeightName);INetSolverWeights ipNetSolverWeights = ipTraceFlowSolver as INetSolverWeights;ipNetSolverWeights.FromToEdgeWeight = ipNetWeight;//开始边线的权重ipNetSolverWeights.ToFromEdgeWeight = ipNetWeight;//终止边线的权重object [] vaRes =new object[intCount-1];//通过findpath得到边线和交汇点的集合ipTraceFlowSolver.FindPath(esriFlowMethod.esriFMConnected,esriShortestPathObjFn.esriSPObjFnMinSum,out m_ipEnumNetEID_Junctions,out m_ipEnumNetEID_Edges, intCount-1, ref vaRes);//计算成本m_dblPathCost = 0;for (int i =0;i<vaRes.Length;i++){double m_Va =(double) vaRes;m_dblPathCost = m_dblPathCost + m_Va;}m_ipPolyline = null;}catch(Exception ex){Console.WriteLine(ex.Message);}}#endregion#region Private Function//初始化private bool InitializeNetworkAndMap(IFeatureDataset FeatureDataset) {IFeatureClassContainer ipFeatureClassContainer;IFeatureClass ipFeatureClass ;IGeoDataset ipGeoDataset;ILayer ipLayer ;IFeatureLayer ipFeatureLayer;IEnvelope ipEnvelope, ipMaxEnvelope ;double dblSearchTol;INetworkCollection ipNetworkCollection = FeatureDataset as INetworkCollection;int count = ipNetworkCollection.GeometricNetworkCount;//获取几何网络工作空间m_ipGeometricNetwork = ipNetworkCollection.get_GeometricNetwork(0); INetwork ipNetwork = m_work;if(m_ipMap!=null){m_ipMap = new MapClass();ipFeatureClassContainer = m_ipGeometricNetwork as IFeatureClassContainer;count = ipFeatureClassContainer.ClassCount;for(int i =0;i<count;i++){ipFeatureClass = ipFeatureClassContainer.get_Class(i); ipFeatureLayer = new FeatureLayerClass();ipFeatureLayer.FeatureClass = ipFeatureClass;m_ipMap.AddLayer( ipFeatureLayer);}}count = m_yerCount;ipMaxEnvelope = new EnvelopeClass();for(int i =0;i<count;i++){ipLayer = m_ipMap.get_Layer(i);ipFeatureLayer = ipLayer as IFeatureLayer;ipGeoDataset = ipFeatureLayer as IGeoDataset;ipEnvelope = ipGeoDataset.Extent;ipMaxEnvelope.Union( ipEnvelope);}m_ipPointToEID = new PointToEIDClass();m_ipPointToEID.SourceMap = m_ipMap;m_ipPointToEID.GeometricNetwork = m_ipGeometricNetwork;double dblWidth = ipMaxEnvelope.Width;double dblHeight = ipMaxEnvelope.Height;if( dblWidth > dblHeight)dblSearchTol = dblWidth / 100;elsedblSearchTol = dblHeight / 100;m_ipPointToEID.SnapTolerance = dblSearchTol;return true ;}private void CloseWorkspace(){m_ipGeometricNetwork = null;m_ipPoints = null;m_ipPointToEID = null;m_ipEnumNetEID_Junctions = null;m_ipEnumNetEID_Edges = null;m_ipPolyline = null;}#endregion}}备注:ClsPathFinder m_ipPathFinder;if(m_ipPathFinder==null)//打开网络空间{m_ipPathFinder = new ClsPathFinder();ipMap = this.m_ActiveView.FocusMap;ipLayer = ipMap.get_Layer(0);ipFeatureLayer = ipLayer as IFeatureLayer;ipFDB = ipFeatureLayer.FeatureClass.FeatureDataset;m_ipPathFinder.SetOrGetMap = ipMap;m_ipPathFinder.OpenFeatureDatasetNetwork(ipFDB);}private void ViewMap_OnMouseDown(object sender,ESRI.ArcGIS.MapControl.IMapControlEvents2_OnMouseDownEvent e)//获取鼠标输入的点{IPoint ipNew ;if( m_ipPoints==null){m_ipPoints = new MultipointClass();m_ipPathFinder.StopPoints = m_ipPoints;}ipNew =ViewMap.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x ,e.y);object o = Type.Missing;m_ipPoints.AddPoint(ipNew,ref o,ref o);}m_ipPathFinder.SolvePath("Weight");//解析路径IPolyline ipPolyResult = m_ipPathFinder.PathPolyLine();//返回最短路径。
cc++图的最短路径Dijkstra(迪杰斯特拉)算法
cc++图的最短路径Dijkstra(迪杰斯特拉)算法c/c++ 图的最短路径 Dijkstra(迪杰斯特拉)算法图的最短路径的概念:⼀位旅客要从城市A到城市B,他希望选择⼀条途中中转次数最少的路线。
假设途中每⼀站都需要换车,则这个问题反映到图上就是要找⼀条从顶点A到B所含边的数量最少的路径。
我们只需从顶点A出发对图作⼴度优先遍历,⼀旦遇到顶点B就终⽌。
由此所得⼴度优先⽣成树上,从根顶点A到顶点B的路径就是中转次数最少的路径。
但是这只是⼀类最简单的图的最短路径问题。
有时,对于旅客来说,可能更关⼼的是节省交通费⽤;⽽对于司机来说,⾥程和速度则是他们感兴趣的的信息。
为了在图上表⽰相关信息,可对边赋以权值,权值可以表⽰两个城市之间的距离,或途中所需时间,或交通费⽤等等。
此时路径长度的度量就不再是路径上边的数⽬,⽽是路径上边权值之和。
实现思路:创建2个辅助int*数组dist path,1个bool数组sdist 存放⽬标顶点到每个顶点的最短距离path 存放⽬标顶点到每个顶点的路径s 被查找过的顶点设置为true,否则为false图为下图1,假设⽬标顶点为A,先从A开始找到各个顶点的权值,A B C D Edist010⽆穷⼤30100path-10000s true false false false falsepath含义:⽐如path[1]=0,就代表从下标为0的顶点(A顶点)到B顶点2,从dist⾥找到s为false的最⼩值,也就是dist[1]的值10,下标1说明是顶点B,再从B开始找到各个顶点的权值,更新dist和path,并设置B 为trueA B C D Edist010*******path-10100s true true false false false3,从dist⾥找到s为false最⼩值,也就是dist[3]的值30,下标3说明是顶点D,再从D开始找到各个顶点的权值,更新dist和path,并设置D为trueA B C D Edist010503090path-10303s true true false true false4,从dist⾥找到s为false最⼩值,也就是dist[2]的值50,下标2说明是顶点C,再从C开始找到各个顶点的权值,更新dist和path,并设置C为trueA B C D Edist010503060path-10302A B C D Es true true true true false5,从dist⾥找到s为false最⼩值,也就是dist[4]的值60,下标4说明是顶点E,再从E开始找到各个顶点的权值,更新dist和path,并设置E为trueA B C D Edist010503060path-10302s true true true true true下⾯两幅图可以帮助理解dijkstra.h#ifndef __mixspantree__#define __mixspantree__#include <stdio.h>#include <malloc.h>#include <assert.h>#include <memory.h>#include <stdlib.h>#include <stdbool.h>#define Default_vertex_size 20#define T char//dai biao ding dian de lei xing#define E int#define MAX_COST 0x7FFFFFFFtypedef struct GraphMtx{int MaxVertices;//zui da ding dian shu liang]int NumVertices;//shi ji ding dian shu liangint NumEdges;//bian de shu lianT* VerticesList;//ding dian listint** Edge;//bian de lian jie xin xi, bu shi 0 jiu shi 1}GraphMtx;//chu shi hua tuvoid init_graph(GraphMtx* gm);//打印⼆维数组void show_graph(GraphMtx* gm);//插⼊顶点void insert_vertex(GraphMtx* gm, T v);//添加顶点间的线void insert_edge(GraphMtx* gm, T v1, T v2, E cost);//最短路径void short_path(GraphMtx* g,T v,E* dist, int* path);#endifdijkstra.c#include "dijkstra.h"void init_graph(GraphMtx* gm){gm->MaxVertices = Default_vertex_size;gm->NumEdges = gm->NumVertices = 0;//kai pi ding dian de nei cun kong jiangm->VerticesList = (T*)malloc(sizeof(T) * (gm->MaxVertices));assert(NULL != gm->VerticesList);//创建⼆维数组//让⼀个int的⼆级指针,指向⼀个有8个int⼀级指针的数组//开辟⼀个能存放gm->MaxVertices个int⼀级指针的内存空间gm->Edge = (int**)malloc(sizeof(int*) * (gm->MaxVertices));assert(NULL != gm->Edge);//开辟gm->MaxVertices组,能存放gm->MaxVertices个int的内存空间 for(int i = 0; i < gm->MaxVertices; ++i){gm->Edge[i] = (int*)malloc(sizeof(int) * gm->MaxVertices);}//初始化⼆维数组//让每个顶点之间的边的关系都为不相连的for(int i = 0; i < gm->MaxVertices; ++i){for(int j = 0; j < gm->MaxVertices; ++j){if(i == j)gm->Edge[i][j] = 0;elsegm->Edge[i][j] = MAX_COST;}}}//打印⼆维数组void show_graph(GraphMtx* gm){printf(" ");for(int i = 0; i < gm->NumVertices; ++i){printf("%3c ", gm->VerticesList[i]);}printf("\n");for(int i = 0; i < gm->NumVertices; ++i){//在⾏⾸,打印出顶点的名字printf("%c:", gm->VerticesList[i]);for(int j = 0; j < gm->NumVertices; ++j){if(gm->Edge[i][j] == MAX_COST){printf("%3c ", '*');}else{printf("%3d ", gm->Edge[i][j]);}}printf("\n");}printf("\n");}//插⼊顶点void insert_vertex(GraphMtx* gm, T v){//顶点空间已满,不能再插⼊顶点了if(gm->NumVertices >= gm->MaxVertices){return;}gm->VerticesList[gm->NumVertices++] = v;}int getVertexIndex(GraphMtx* gm, T v){for(int i = 0; i < gm->NumVertices; ++i){if(gm->VerticesList[i] == v)return i;}return -1;}//添加顶点间的线void insert_edge(GraphMtx* gm, T v1, T v2, E cost){if(v1 == v2)return;//查找2个顶点的下标int j = getVertexIndex(gm, v1);int k = getVertexIndex(gm, v2);//说明找到顶点了,并且点之间还没有线if(j != -1 && k != -1 ){//因为是有⽅向,所以更新1个值gm->Edge[j][k] = cost;//边数加⼀gm->NumEdges++;}}//取得2个顶点之间的权值E getWeight(GraphMtx* g, int v1, int v2){if(v1 == -1 || v2 == -1) return MAX_COST;return g->Edge[v1][v2];}//最短路径void short_path(GraphMtx* g,T v,E* dist, int* path){int n = g->NumVertices;bool* s = (bool*)malloc(sizeof(bool) * n);assert(NULL != s);int vi = getVertexIndex(g, v);for(int i = 0; i < n; ++i){//获得各个顶点与⽬标顶点之间的权值dist[i] = getWeight(g, vi, i);s[i] = false;if(i != vi && dist[i] < MAX_COST){path[i] = vi;}else{path[i] = -1;}}s[vi] = true;int min;int w;for(int i = 0; i < n - 1; ++i){min = MAX_COST;//u为最短路径顶点的下标int u = vi;for(int j = 0; j < n; ++j){if(!s[j] && dist[j] < min){u = j;min = dist[j];}}//把u加⼊到s集合s[u] = true;//更新下⼀个点到所有点的权值for(int k = 0; k < n; ++k){w = getWeight(g, u, k);if(!s[k] && w < MAX_COST && dist[u] + w < dist[k]){ dist[k] = dist[u] + w;path[k] = u;}}}}dijkstramain.c#include "dijkstra.h"int main(){GraphMtx gm;//初始化图init_graph(&gm);//插⼊顶点insert_vertex(&gm, 'A');insert_vertex(&gm, 'B');insert_vertex(&gm, 'C');insert_vertex(&gm, 'D');insert_vertex(&gm, 'E');//添加连线insert_edge(&gm, 'A', 'B', 10);insert_edge(&gm, 'A', 'D', 30);insert_edge(&gm, 'A', 'E', 100);insert_edge(&gm, 'B', 'C', 50);insert_edge(&gm, 'C', 'E', 10);insert_edge(&gm, 'D', 'C', 20);insert_edge(&gm, 'D', 'E', 60);//打印图show_graph(&gm);int n = gm.NumVertices;E* dist = (E*)malloc(sizeof(E) * n);int* path = (int*)malloc(sizeof(int) * n);assert(NULL != dist && NULL != path);//最短路径short_path(&gm, 'A', dist, path);}编译⽅法:gcc -g dijkstra.c dijkstramain.c 执⾏结果如下图:。
c++最短路径算法和充电问题
在计算机科学领域,最短路径算法是一类重要的算法,可以帮助我们找到图中两个顶点之间的最短路径。
而在现实生活中,充电问题也是一个备受关注的话题,特别是在智能手机、电动车等设备普及的今天,人们对于如何高效地给这些设备充电也越来越感兴趣。
C++是一种高效、灵活的编程语言,它有着丰富的库函数和工具,使得我们可以很方便地实现最短路径算法和解决充电问题。
在本文中,我们将从简到繁地探讨C++最短路径算法和充电问题,并对它们进行全面评估。
一、最短路径算法1. Dijkstra算法Dijkstra算法是一种经典的最短路径算法,它可以在带权重的图中找到单源最短路径。
在C++语言中,我们可以使用STL库中的priority_queue和vector来实现Dijkstra算法,通过使用最小堆来维护当前离源点最近的节点,同时动态更新节点的最短路径值。
2. Floyd-Warshall算法Floyd-Warshall算法是一种多源最短路径算法,它可以有效地处理带权重的有向图或无向图。
在C++中,我们可以使用二维数组来表示节点之间的距离关系,并通过动态规划的方式逐步更新最短路径值。
3. Bellman-Ford算法Bellman-Ford算法是一种解决带有负权边的最短路径问题的算法,它可以检测出图中是否存在负权回路,并找出最短路径。
在C++中,我们可以使用数组来表示节点的最短路径值,并通过对每条边进行多次松弛操作来逐步逼近最短路径值。
二、充电问题在现代社会,充电问题已经成为了人们生活中不可或缺的一部分。
无论是手机、电动车还是笔记本电脑,它们都需要不断地充电以保持正常使用。
在这样的背景下,如何高效地解决充电问题就显得尤为重要。
1. 充电桩的分布充电桩的分布对充电问题有着重要的影响。
在城市中,如果充电桩分布得当,可以有效地解决人们出行中的充电问题,提高出行的便捷性。
在C++中,我们可以使用图论算法来模拟充电桩的分布,找到最佳的布局方案。
C语言自动生成查找迷宫最短路径的代码
C语言自动生成查找迷宫最短路径的代码#include#include#include#include#includeusing namespace std;#define OVERFLOW 0#define OK 1#define ERROE 0#define TRUE 1#define FALSE 0#define SIZE 102//迷宫的最大范围typedef int Status;typedef struct{int x;int y;}PosType;//坐标位置typedef struct {PosType seat; //通道块在迷宫中的"坐标位置"int di; //从上一通道块走向此通道块的"方向"}SElemType;void Random(int (*mg)[SIZE],int size,PosType start,PosType end);/*随机生成迷宫的函数/*为了能够让尽量能通过,将能通过的块和不能通过的块数量比大致为3:1*/Status Pass(PosType e,int (*mg)[SIZE]);//当前块可否通过Status FootPrint(PosType e,int (*mg)[SIZE]);//留下通过的足迹PosType NextPos(PosType e,int dir);//下一步Status Equal(PosType e1,PosType e2);//e1与e2的位置坐标是否相同Status MarkPath(PosType e,int (*mg)[SIZE],int di);//对最短可行路径上的“通道块”进行标记PosType FrontPos(PosType e,int dir);//寻找当前通道块的上一步的位置Status PathPrint(stack s,int (*mg)[SIZE]);//迷宫最短路径的标记Status PathClean(int (*mg)[SIZE],stack s);//路径清除Status MazePath(PosType start,PosType end,int (*mg)[SIZE],stack &s);/*迷宫函数/* 若迷宫maze中从入口start到出口end的通道,则求得一条存放在栈中/* 并返回TRUE;否则返回FALSE*/void PrintMaze(int (*mg)[SIZE],int size);//打印迷宫Status Check(char &choice);//确认输入正确int main(){stack s;int mg[SIZE][SIZE]={1},size;PosType start,end;char choice;system("mode con cols=220 lines=220");printf("\n==================迷宫最短路径游戏==================");printf("\n说明:■不能走的区域");printf("\n '空格'代表可通过的区域");printf("\n默认起点为左上角位置,默认终点为右下角位置\n");printf("\n================================ ============\n");printf("请输入迷宫边长(3~%d),系统将为你产生一个随机迷宫:",SIZE-2);scanf("%d",&size);while((size>SIZE-2)||(size<1)){printf("输入有误!\n");printf("请输入迷宫边长(3~%d),系统将为你产生一个随机迷宫:",SIZE-2);scanf("%d",&size);}size+=2;//补上外围getchar();//跳过'\n'start.x=1;start.y=1; //起点坐标end.x=size-2;end.y=size-2; //终点坐标Random(mg,size,start,end);PrintMaze(mg,size);while(!((choice=='Q')||(choice=='q'))){printf("是否使用该迷宫?(y/n)\n");Check(choice);if((choice=='Y')||(choice=='y')){PathClean(mg,s);}while((choice=='n')||(choice=='N')){while(!s.empty())s.pop();choice=' ';printf("请输入迷宫边长(3~%d),系统将为你产生一个随机迷宫:",SIZE-2);scanf("%d",&size);while((size>SIZE-2)||(size<1)){printf("输入有误!\n");printf("请输入迷宫边长(3~%d),系统将为你产生一个随机迷宫:",SIZE-2);scanf("%d",&size);}size+=2;//补上外围start.x=1;start.y=1;//起点坐标end.x=size-2;end.y=size-2; //终点坐标getchar();//跳过'\n'Random(mg,size,start,end);PrintMaze(mg,size);printf("是否使用该迷宫?(y/n)\n");Check(choice);}printf("是否人工选择起点和终点(y/n)?【默认:起点(1,1),终点(%d,%d)】\n",size-2,size-2);Check(choice);if((choice=='y')||(choice=='Y')){printf("请输入“起点”坐标(1~%d)用空格分隔:",size-2);scanf("%d %d",&start.x,&start.y);while(((start.x>size-2)||start.x<1)||((start.y>size-2)||(start.y<1))||!Pass(start,mg)){if(!Pass(start,mg)) printf("些位置不能为“起点”!\n");else printf("输入有误!\n");printf("请输入“起点”坐标(1~%d)用空格分隔:",size-2);scanf("%d %d",&start.x,&start.y);}printf("请输入“终点”坐标(1~%d)用空格分隔:",size-2);scanf("%d %d",&end.x,&end.y);while(((end.x>size-2)||end.x<1)||((end.y>size-2)||(end.y<1))||!Pass(end,mg)||Equal(start,end)){if(!Pass(end,mg)) printf("些位置不能为“终点”!\n");else if(Equal(start,end)) printf("该位置已为起点!\n");else printf("输入有误!\n");printf("请输入“终点”坐标(1~%d)用空格分隔:",size-2);scanf("%d %d",&end.x,&end.y);}getchar();//跳过'\n'}MazePath(start,end,mg,s);PrintMaze(mg,size);printf("退出游戏请输入\"Q\"否则继续游戏!\n");choice=getchar();getchar();//跳过'\n'}printf("\n==========程序退出,感谢使用!==========\n");return 0;}void Random(int (*mg)[SIZE],int size,PosType start,PosType end){int i,j,k;srand(time(NULL));for(j=0;j<size;j++)mg[0][j]=mg[size-1][j]=1; /*设置迷宫外围"不可走",保证只有一个出口和入口*/for(i=1;i<size-1;i++)mg[i][0]=mg[i][size-1]=1; /*设置迷宫外围"不可走",保证只有一个出口和入口*/for(i=1;i<size-1;i++)for(j=1;j<size-1;j++){k=rand()%4; //随机生成0、1、2、4三个数if(k)mg[i][j]=0;else{mg[i][j]=1;}//else}mg[start.y][start.x]=0;mg[end.y][end.x]=0; //将入口、出口设置为"0"即可通过}Status Pass(PosType e,int (*mg)[SIZE]){if (mg[e.y][e.x]==0) //0时可以通过return OK; // 如果当前位置是可以通过,返回1 return OVERFLOW; // 其它情况返回0}Status FootPrint(PosType e,int (*mg)[SIZE]){mg[e.y][e.x]=7;return OK;}PosType NextPos(PosType e,int dir){PosType E;switch(dir){case 1:E.x=e.x+1; //向右E.y=e.y;break;case 2:E.x=e.x; //向下E.y=e.y+1;break;case 3:E.x=e.x-1; //向左E.y=e.y;break;case 4:E.x=e.x; //向上E.y=</size-1;j++){</size-1;i++)</size-1;i++)</size;j++)e.y-1;break;}return E;}Status Equal(PosType e1,PosType e2){if((e1.x==e2.x)&&(e1.y==e2.y))return TRUE;return FALSE;}Status MarkPath(PosType e,int (*mg)[SIZE],int di) {switch(di){case 1://向右mg[e.y][e.x]=11;break;case 2://向下mg[e.y][e.x]=12;break;case 3://向左mg[e.y][e.x]=13;break;case 4://向上mg[e.y][e.x]=14;break;}return OK;}PosType FrontPos(PosType e,int dir) {PosType E;switch(dir){case 1:E.x=e.x-1; //向左E.y=e.y;break;case 2:E.x=e.x; //向上E.y=e.y-1;break;case 3:E.x=e.x+1; //向右E.y=e.y;break;case 4:E.x=e.x; //向下E.y=e.y+1;break;}return E;}Status PathPrint(stack s,int (*mg)[SIZE]) {SElemType e,front,tail;int di;e=s.top();tail=e;s.pop();MarkPath(e.seat,mg,1);while(!s.empty()){front=s.top();s.pop();if(Equal(front.seat,FrontPos(e.seat,e.di))) {di=e.di;e=front;MarkPath(e.seat,mg,di);}}mg[tail.seat.y][tail.seat.x]=20;mg[e.seat.y][e.seat.x]=10;return OK;Status PathClean(int (*mg)[SIZE],stack s){SElemType e;while(!s.empty()){e=s.top();s.pop();mg[e.seat.y][e.seat.x]=0;}return OK;}Status MazePath(PosType start,PosType end,int (*mg)[SIZE],stack &s){queue q;SElemType e;int di=0;e.di=di;e.seat=start;// 设定"当前位置"为"入口位置"q.push(e);s.push(e);do{e=q.front();q.pop();for(di=1;di<=4;di++)e.seat=NextPos(e.seat,di);e.di=di;if(Pass(e.seat,mg)){q.push(e);s.push(e);FootPrint(e.seat,mg);if(Equal(e.seat,end)){PathPrint(s,mg);return TRUE;}}e.seat=FrontPos(e.seat,di);}}while(!q.empty());printf("\n\n囧 ! 不能到达终点!"); return FALSE;}void PrintMaze(int (*mg)[SIZE],int size) {int i,j;printf("\n");for(i=0;i<size;i++){for(j=0;j<size;j++){switch(mg[i][j]){case 0: case 7: printf(" "); break; case 1: printf("■"); break; case 10: printf("起"); break; case 20: printf("终"); break; case 11: printf("→"); break; case 12: printf("↓"); break; case 13: printf("←"); break; case 14: printf("↑"); break;}}printf("\n"); }printf("\n");}Status Check(char &choice){while(!(((choice=getchar())=='y')||(choice=='n')||(choice=='Y ')||(choice=='N')))//非正确输入{if(choice!='\n'){printf("请输入确定选择(y/n)\n");getchar();}}getchar();//跳过'\n'return OK;}</size;j++){</size;i++){。
ArcGIS网络分析最短路径分析源代码(VB6.0)
ArcGIS⽹络分析最短路径分析源代码(VB6.0)ArcGIS⽹络分析最短路径分析源代码(VB6.0)12' Copyright 1995-2005 ESRI34' All rights reserved under the copyright laws of the United States.56' You m ay freely redistribute and use this sam ple code, with or without m odifi cation.78' Disclaimer: THE SAMPLE CODE IS PROVIDED "AS IS" AND ANY EXPRESS O R IMPLIED9' WARRANTIES, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILIT Y AND FITNESS10' FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ESR I OR11' CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE CIAL, EXEMPLARY,12' OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROC UREMENT OF13' SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; O R BUSINESS14' INTERRUPTION) SUSTAINED BY YOU OR A THIRD PARTY, HOWEVER CAUSE D AND ON ANY15' THEORY OF LIABILITY, WHETHER IN CONT RACT, STRICT LIABILITY, OR TO RT ARISING IN ANY16' WAY OUT OF THE USE OF THIS SAMPLE CODE, EVEN IF ADVISED OF THE P OSSIBILITY OF17' SUCH DAMAGE.1819' For additional information contact: Environmental System s Research Institu te, Inc.2021' Attn: Contracts Dept.2223' 380 New York Street2425' Redlands, California, U.S.A. 923732627' Em ail: contracts@/doc/07098e37f111f18583d05ab5.html2829Option Explicit3031' vb version of the PathFinder object3233' 本地变量34Private m_ipGeometricNetwork As esriGeoDatabase.IGeometricNetwork35Private m_ipMap As esriCarto.IMap36Private m_ipPoints As esriGeometry.IPointCollection37Private m_ipPointToEID As esriNetworkAnalysis.IPointToEID38' 返回结果变量39Private m_dblPathCost As Double40Private m_ipEnumNetEID_Junctions As esriGeoDatabase.IEnumNetEID41Private m_ipEnumNetEID_Edges As esriGeoDatabase.IEnumNetEID42Private m_ipPolyline As esriGeometry.IPolyline434445' Optionally set the Map (e.g. the current m ap in ArcMap),46' otherwise a default m ap will be made (for IPointToEID).48Public Property Set Map(Map As esriCarto.IMap)49Set m_ipMap = Map50End Property5152Public Property Get Map() As esriCarto.IMap53Set Map = m_ipMap54End Property5556' Either OpenAccessNetwork or OpenFeatureDatasetNetwork57' needs to be called.5859Public Sub OpenAccessNetwork(AccessFileName As String, FeatureDatasetNa me As String)6061Dim ipWorkspaceFactory As esriGeoDatabase.IWorkspaceFactory62Dim ipWorkspace As esriGeoDatabase.IWorkspace63Dim ipFeatureWorkspace As esriGeoDatabase.IFeatureWorkspace64Dim ipFeatureDataset As esriGeoDatabase.IFeatureDataset6566' After this Sub exits, we'll have an INetwork interface67' and an IMap interface initialized for the network we'll be using.6869' close down the last one if opened70 CloseWorkspace7172' open the m db73Set ipWorkspaceFactory =New esriDataSourcesGDB.AccessWorkspaceFact ory74Set ipWorkspace = ipWorkspaceFactory.OpenFromFile(AccessFileName, 0)76' get the FeatureWorkspace77Set ipFeatureWorkspace = ipWorkspace7879' open the FeatureDataset80Set ipFeatureDataset = ipFeatureWorkspace.OpenFeatureDataset(FeatureD atasetNam e)8182' initialize Network and Map (m_ipNetwork, m_ipMap)83If Not InitializeNetworkAndMap(ipFeatureDataset) Then Err.Raise 0, "Open AccessNetwork", "Error initializing Network and Map"8485End Sub8687Public Sub OpenFeatureDatasetNetwork(FeatureDataset As esriGeoDatabase. IFeatureDataset)88' close down the last one if opened89 CloseWorkspace9091' we assum e that the caller has passed a valid FeatureDataset9293' initialize Network and Map (m_ipNetwork, m_ipMap)94If Not InitializeNetworkAndMap(FeatureDataset) Then Err.Raise 0, "OpenFe atureDatasetNetwork", "Error initializing Network and Map"9596End Sub9798' The collection of points to travel through must be set.99100Public Property Set StopPoints(Points As esriGeometry.IPointCollection)102End Property103104Public Property Get StopPoints() As esriGeometry.IPointCollection105Set StopPoints = m_ipPoints106End Property107108' Calculate the path109110Public Sub SolvePath(WeightName As String)111112Dim ipNetwork As esriGeoDatabase.INetwork113Dim ipTraceFlowSolver As esriNetworkAnalysis.ITraceFlowSolver114Dim ipNetSolver As esriNetworkAnalysis.INetSolver115Dim ipNetFlag As esriNetworkAnalysis.INetFlag116Dim ipaNetFlag() As esriNetworkAnalysis.IEdgeFlag117Dim ipEdgePoint As esriGeometry.IPoint118Dim ipNetElements As esriGeoDatabase.INetElements119Dim intEdgeUserClassID As Long120Dim intEdgeUserID As Long121Dim intEdgeUserSubID As Long122Dim intEdgeID As Long123Dim ipFoundEdgePoint As esriGeometry.IPoint124Dim dblEdgePercent As Double125Dim ipNetWeight As esriGeoDatabase.INetWeight126Dim ipNetSolverWeights As esriNetworkAnalysis.INetSolverWeights127Dim ipNetSchem a As esriGeoDatabase.INetSchem a128Dim intCount As Long129Dim i As Long130Dim vaRes() As Variant132' m ake sure we are ready133 Debug.Assert Not m_ipPoints Is Nothing134 Debug.Assert Not m_ipGeometricNetwork Is Nothing135136' instantiate a trace flow solver137Set ipTraceFlowSolver = New esriNetworkAnalysis.TraceFlowSolver138139' get the INetSolver interface140Set ipNetSolver = ipTraceFlowSolver141142' set the source network to solve on143Set ipNetwork = m_/doc/07098e37f111f18583d05ab5.html work144Set ipNetSolver.SourceNetwork = ipNetwork145146' m ake edge flags from the points147148' the INetElements interface is needed to get UserID, UserClassID,149' and UserSubID from an element id150Set ipNetElements = ipNetwork151152' get the count153 intCount = m_ipPoints.PointCount154 Debug.Assert intCount > 1155156' dimension our IEdgeFlag array157ReDim ipaNetFlag(intCount)158159For i = 0 To intCount - 1160' m ake a new Edge Flag162Set ipEdgePoint = m_ipPoints.Point(i)163' look up the EID for the current point (this will populate intEdgeID and d blEdgePercent)164 m_ipPointToEID.GetNearestEdge ipEdgePoint, intEdgeID, ipFoundEdgePoi nt, dblEdgePercent165 Debug.Assert intEdgeID > 0 ' else Point (eid) not found166 ipNetElements.QueryIDs intEdgeID, esriETEdge, intEdgeUserClassID, intE dgeUserID, intEdgeUserSubID167 Debug.Assert (intEdgeUserClassID > 0) And (intEdgeUserID > 0) ' else P oint not found168 /doc/07098e37f111f18583d05ab5.html erClassID = intEdgeUserClassID169 /doc/07098e37f111f18583d05ab5.html erID = intEdgeUserID170 /doc/07098e37f111f18583d05ab5.html erSubID = intEdgeUserSubID171Set ipaNetFlag(i) = ipNetFlag172Next173174' add these edge flags175 ipTraceFlowSolver.PutEdgeOrigins intCount, ipaNetFlag(0)176177' set the weight (cost field) to solve on178179' get the INetSchem a interface180Set ipNetSchem a = ipNetwork181Set ipNetWeight = ipNetSchem a.WeightByName(WeightName)182 Debug.Assert Not ipNetWeight Is Nothing183184' set the weight (use the sam e for both directions)185Set ipNetSolverWeights = ipTraceFlowSolver186Set ipNetSolverWeights.From ToEdgeWeight = ipNetWeight188189' initialize array for results to number of segments in result190ReDim vaRes(intCount - 1)191192' solve it193 ipTraceFlowSolver.FindPath esriFMConnected, esriSPObjFnMinSum, m_ipEn umNetEID_Junctions, m_ipEnumNetEID_Edges, intCount - 1, vaRes(0)194195' com pute total cost196 m_dblPathCost = 0197For i =LBound(vaRes) To UBound(vaRes)198 m_dblPathCost = m_dblPathCost + vaRes(i)199Next200201' clear the last polyline result202Set m_ipPolyline =Nothing203204End Sub205206' Property to get the cost207208Public Property Get PathCost() As Double209 PathCost = m_dblPathCost210End Property211212' Property to get the shape213214Public Property Get PathPolyLine() As esriGeometry.IPolyline215217Dim count As Long, i As Long218Dim ipEIDInfo As esriNetworkAnalysis.IEIDInfo219Dim ipEnumEIDInfo As esriNetworkAnalysis.IEnumEIDInfo220Dim ipGeometry As esriGeometry.IGeometry221Dim ipNewGeometryColl As esriGeometry.IGeometryCollection222Dim ipSpatialReference As esriGeometry.ISpatialReference223224' if the line is already computed since the last path, just return it225If Not m_ipPolyline Is Nothing Then226Set PathPolyLine = m_ipPolyline227Exit Property228End If229230Set m_ipPolyline =New esriGeometry.Polyline231Set ipNewGeometryColl = m_ipPolyline232233' a path should be solved first234 Debug.Assert Not m_ipEnumNetEID_Edges Is Nothing235236' m ake an EIDHelper object to translate edges to geom etric features237Set ipEIDHelper =New esriNetworkAnalysis.EIDHelper238Set ipEIDHelper.GeometricNetwork = m_ipGeometricNetwork239Set ipSpatialReference = m_ipMap.SpatialReference240Set ipEIDHelper.OutputSpatialReference = ipSpatialReference241 ipEIDHelper.ReturnGeometries =True242243' get the details using the IEIDHelper classes244Set ipEnumEIDInfo = ipEIDHelper.CreateEnumEIDInfo(m_ipEnumNetEID_ Edges)247' set the iterator to beginning248 ipEnumEIDInfo.Reset249250For i = 1 To count251252' get the next EID and a copy of its geom etry (it m akes a Clone)253Set ipEIDInfo = ipEnumEIDInfo.Next254Set ipGeom etry = ipEIDInfo.Geometry255256 ipNewGeometryColl.AddGeometryCollection ipGeometry257258Next' EID259260' return the m erged geometry as a Polyline261Set PathPolyLine = m_ipPolyline262263End Property264265' Private266267Private Sub CloseWorkspace()268' m ake sure we let go of everything and start with new results269Set m_ipGeometricNetwork =Nothing270Set m_ipPoints =Nothing271Set m_ipPointToEID = Nothing272Set m_ipEnumNetEID_Junctions =Nothing273Set m_ipEnumNetEID_Edges =Nothing274Set m_ipPolyline =Nothing277Private Function InitializeNetworkAndMap(FeatureDataset As esriGeoDataba se.IFeatureDataset) As Boolean278279Dim ipNetworkCollection As esriGeoDatabase.INetworkCollection280Dim ipNetwork As esriGeoDatabase.INetwork281Dim count As Long, i As Long282Dim ipFeatureClassContainer As esriGeoDatabase.IFeatureClassContainer283Dim ipFeatureClass As esriGeoDatabase.IFeatureClass284Dim ipGeoDataset As esriGeoDatabase.IGeoDataset285Dim ipLayer As esriCarto.ILayer286Dim ipFeatureLayer As esriCarto.IFeatureLayer287Dim ipEnvelope As esriGeometry.IEnvelope, ipMaxEnvelope As esriGeomet ry.IEnvelope288Dim dblSearchTol As Double289Dim dblWidth As Double, dblHeight As Double290291On Error GoTo Trouble292293' get the networks294Set ipNetworkCollection = FeatureDataset295296' even though a FeatureDataset can have m any networks, we'll just297' assum e the first one (otherwise you would pass the network name in, et c.)298299' get the count of networks300 count = ipNetworkCollection.GeometricNetworkCount301304' get the first Geometric Newtork (0 - based)305Set m_ipGeometricNetwork = ipNetworkCollection.GeometricNetwork(0)306307' get the Network308Set ipNetwork = m_/doc/07098e37f111f18583d05ab5.html work309310' The EID Helper class that converts points to EIDs needs a311' IMap, so we'll need one around with all our layers added.312' This Pathfinder object has an optional Map property than m ay be set313' before opening the Network.314If m_ipMap Is Nothing Then315Set m_ipMap = New esriCarto.Map316317' Add each of the Feature Classes in this Geometric Network as a m ap Lay er318Set ipFeatureClassContainer = m_ipGeometricNetwork319 count = ipFeatureClassContainer.ClassCount320 Debug.Assert count > 0 ' then Exception.Create('No (network) feature cl asses found');321322For i = 0 To count - 1323' get the feature class324Set ipFeatureClass = ipFeatureClassContainer.Class(i)325' m ake a layer326Set ipFeatureLayer = New esriCarto.FeatureLayer327Set ipFeatureLayer.FeatureClass = ipFeatureClass328' add layer to the m ap329 m_ipMap.AddLayer ipFeatureLayer331End If' we needed to m ake a Map332333334' Calculate point snap tolerance as 1/100 of m ap width.335 count = m_/doc/07098e37f111f18583d05ab5.html yerCount336Set ipMaxEnvelope =New esriGeometry.Envelope337For i = 0 To count - 1338Set ipLayer = m_/doc/07098e37f111f18583d05ab5.html yer(i)339Set ipFeatureLayer = ipLayer340' get its dim ensions (for setting search tolerance)341Set ipGeoDataset = ipFeatureLayer342Set ipEnvelope = ipGeoDataset.Extent343' m erge with m ax dim ensions344 ipMaxEnvelope.Union ipEnvelope345Next346347' finally, we can set up the IPointToEID348Set m_ipPointToEID = New esriNetworkAnalysis.PointToEID349Set m_ipPointToEID.SourceMap = m_ipMap350Set m_ipPointToEID.GeometricNetwork = m_ipGeometricNetwork351352' set snap tolerance353 dblWidth = ipMaxEnvelope.Width354 dblHeight = ipMaxEnvelope.Height355356If dblWidth > dblHeight Then357 dblSearchTol = dblWidth / 100#358Else359 dblSearchTol = dblHeight / 100#360End If361362 m_ipPointToEID.SnapTolerance = dblSearchTol363364 InitializeNetworkAndMap =True' good to go365Exit Function366367Trouble:368 InitializeNetworkAndMap =False' we had an error369End Function。
ArcGIS_7 最短路径问题分析与应用
综合实习7:最短路径问题分析与应用1.背景在现实中,最短路径的求取问题可以拓展为许多方面的最高效率问题,最短路径不仅指一般意义上的距离最短,还可以是时间最短、费用最少、线路利用率最高等标准。
2.目的学会用ArcGIS10进行各种类型的最短路径分析,理解网络分析原理。
3.数据GeoDatabase地理数据库:City.mdb。
数据库中包含一个数据库:City,其中含有城市交通网net、商业中心及家庭住址place、网络节点city_Net_Junctions等要素。
4.要求根据不同的要求,获得到达指定目的地的最佳路径,并给出路径的长度;找出距景点最近的某设施的路径。
在网络中指定一个商业中心,分别求出在不同距离、时间的限制下从家到商业中心的最佳路径。
给定访问顺序,按要求找出从家出发,逐个经过访问点,最终到达目的地的最佳路径。
研究阻强的设置对最佳路径选择的影响。
5.操作步骤启动ArcMap,打开city.mdb,双击city数据库,加载数据。
对点状要素place符号化:以HOME字段,1值为家,0值为商业中心。
(1)无权重最佳路径的生成1)在几何网络分析工具条上,选择旗标工具,将旗标放在“家”和想要取得“商业中心”点上。
2)选择分析|选项命令,打开“分析选项”对话框,确认“权重”和“权重过滤器”标签项全部是“无(None)”,这种情况下进行的最短路径分析是完全按照这个网络自身的长短来确定。
3)在“追踪任务”文本框中选择“网络路径分析”。
单击“解决”按钮。
显示出最短路径(图7-1),这条路径的总成本显示在状态栏中。
图7-1 无权重参照的最短路径的显示(2)加权最佳路径生成1)在几何网络分析工具条上,点选旗标工具,将旗标分别放在“家”和想去的某个“商业中心”的位置上。
2)选择“分析|选项”命令,打开“分析选项”对话框(图7-2)进入“权重”标签页,在边的权重(Edge weights)上,全部选择长度(length)权重属性。
GIS软件工程实习报告(最短路径分析)
AE开发之基于几何网络的最短路径分析1、实习目的本次实习目的在于熟练掌握ArcGIS Engine开发工具并能够通过C#语言在VS 2010开发环境中完成查询几何网络的最短路径分析的功能。
2、实习时间2015年5月23日星期六3、实习容3.1实验环境操作系统:Windows 2007二次开发平台:VS 2010开发环境、ArcGIS Desktop10.0、AE开发组件3.2实验任务完成基于几何网络分析的最短路径查询功能,即实现通过在几何网络地图中指定起始点,能够查询经过起始点的最短路线,并能够通过缩放功能在地图窗口居中显示。
3.3实验步骤3.3.1新建项目选择\文件\新建项目,如图选择项目类型中Visual C#,再选择Windows Application,记为“FindShortPath”,点击确定。
3.3.2添加控件3.3.3控件绑定因为添加的控件只是单独存在,但是程序需要各控件间协同工作,因此要进行控件绑定。
3.3.4创建几何网络1.在ArcCataLog中新建个人地理数据库—“甘地的个人地理数据库”,然后新建要素数据集“road”,接着,鼠标右键选择要素数据集“road”,选择“导入要素类”,导入需要创建几何网络的要素类“主要公路”,输出要素类的名字改为“road”,如下图所示:2.鼠标右键选择要素数据集“road”,选择新建“几何网络”,则出现“新建几何网络”对话框,作如下图所示的一系列设置,最终得到几何网络“road_Net”。
至此,得到几何网络“road_Net”,如下图所示:3.3.5代码实现最短路径分析①设置ToolStrip1②添加代码private IActiveView m_ipActiveView;private IMap m_ipMap;//地图控件中地图private IGraphicsContainer pGC;//图形对象private bool clicked = false;int clickedcount = 0;private double m_dblPathCost = 0;private IGeometricNetwork m_ipGeometricNetwork;private IPointCollection m_ipPoints;//输入点集合private IPointToEID m_ipPointToEID;private IEnumNetEID m_ipEnumNetEID_Junctions;private IEnumNetEID m_ipEnumNetEID_Edges;private IPolyline m_ipPolyline;private IMapControl3 mapctrlMainMap = null;private void Form1_Load(object sender, EventArgs e){//对象初始化mapctrlMainMap = (IMapControl3)this.axMapControl1.Object;m_ipActiveView = axMapControl1.ActiveView;m_ipMap = m_ipActiveView.FocusMap;clicked = false;pGC = m_ipMap as IGraphicsContainer;}private void Findpath_Click(object sender, EventArgs e){mapctrlMainMap.CurrentTool = null;//设置鼠标样式axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;if (yerCount == 0){MessageBox.Show("请先加载几何网络数据!");return;}m_ipActiveView = axMapControl1.ActiveView;m_ipMap = m_ipActiveView.FocusMap;clicked = false;pGC = m_ipMap as IGraphicsContainer;ILayer ipLayer = m_ipMap.get_Layer(0);IFeatureLayer ipFeatureLayer = ipLayer as IFeatureLayer;IFeatureDataset ipFDS = ipFeatureLayer.FeatureClass.FeatureDataset;OpenFeatureDatasetNetwork(ipFDS);clicked = true;clickedcount = 0;pGC.DeleteAllElements();}private void SolvePath_Click(object sender, EventArgs e){axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault;if (SolvePathGan("Weight"))//先解析路径{IPolyline ipPolyResult = PathPolyLine();//最后返回最短路径clicked = false;if (ipPolyResult.IsEmpty){MessageBox.Show("没有路径可到!!");}else{IRgbColor color = new RgbColorClass();color.Red = 255;color.Blue = 64;color.Green = 128;LineElementClass element = new LineElementClass();ILineSymbol linesymbol = new SimpleLineSymbolClass();linesymbol.Color = color as IColor;linesymbol.Width = 3;element.Geometry = m_ipPolyline;element.Symbol = linesymbol;pGC.AddElement(element, 0);m_ipActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);axMapControl1.FlashShape(element.Geometry);MessageBox.Show("路径经过" + m_ipEnumNetEID_Edges.Count + "条线" + "\r\n" + "经过节点数为" + m_ipEnumNetEID_Junctions.Count + "\r\n" + "路线长度为" + m_ipPolyline.Length.ToString("#######.##") + "\r\n", "几何路径信息");}}}//路径缩放功能private void SuoFang_Click(object sender, EventArgs e){if (m_ipPolyline == null){MessageBox.Show("当前没有执行路径查询!!!请确认!");}else{this.axMapControl1.Extent = m_ipPolyline.Envelope;}}#region 自定义路径查询函数public void OpenFeatureDatasetNetwork(IFeatureDataset FeatureDataset){CloseWorkspace();if (!InitializeNetworkAndMap(FeatureDataset))Console.WriteLine("打开network出错");}//关闭工作空间private void CloseWorkspace(){m_ipGeometricNetwork = null;m_ipPoints = null;m_ipPointToEID = null;m_ipEnumNetEID_Junctions = null;m_ipEnumNetEID_Edges = null;m_ipPolyline = null;}//初始化几何网络和地图private bool InitializeNetworkAndMap(IFeatureDataset FeatureDataset){IFeatureClassContainer ipFeatureClassContainer;IFeatureClass ipFeatureClass;IGeoDataset ipGeoDataset;ILayer ipLayer;IFeatureLayer ipFeatureLayer;IEnvelope ipEnvelope, ipMaxEnvelope;double dblSearchTol;INetworkCollection ipNetworkCollection = FeatureDataset as INetworkCollection;int count = ipNetworkCollection.GeometricNetworkCount;//获取第一个几何网络工作空间m_ipGeometricNetwork = ipNetworkCollection.get_GeometricNetwork(0);INetwork ipNetwork = m_work;if (m_ipMap != null){ipFeatureClassContainer = m_ipGeometricNetwork as IFeatureClassContainer;count = ipFeatureClassContainer.ClassCount;for (int i = 0; i < count; i++){ipFeatureClass = ipFeatureClassContainer.get_Class(i);ipFeatureLayer = new FeatureLayerClass();ipFeatureLayer.FeatureClass = ipFeatureClass;for (int j = 0; j < m_yerCount; j++){if (m_ipMap.get_Layer(j).Name.ToUpper() == .ToUpper()){continue;}}}}count = m_yerCount;ipMaxEnvelope = new EnvelopeClass();for (int i = 0; i < count; i++){ipLayer = m_ipMap.get_Layer(i);ipFeatureLayer = ipLayer as IFeatureLayer;ipGeoDataset = ipFeatureLayer as IGeoDataset;ipEnvelope = ipGeoDataset.Extent;ipMaxEnvelope.Union(ipEnvelope);}m_ipPointToEID = new PointToEIDClass();m_ipPointToEID.SourceMap = m_ipMap;m_ipPointToEID.GeometricNetwork = m_ipGeometricNetwork;double dblWidth = ipMaxEnvelope.Width;double dblHeight = ipMaxEnvelope.Height;if (dblWidth > dblHeight)dblSearchTol = dblWidth / 100;elsedblSearchTol = dblHeight / 100;m_ipPointToEID.SnapTolerance = dblSearchTol;return true;}//返回路径的几何体public IPolyline PathPolyLine(){IEIDInfo ipEIDInfo;IGeometry ipGeometry;if (m_ipPolyline != null) return m_ipPolyline;m_ipPolyline = new PolylineClass();IGeometryCollection ipNewGeometryColl = m_ipPolyline as IGeometryCollection;//引用传递ISpatialReference ipSpatialReference = m_ipMap.SpatialReference;IEIDHelper ipEIDHelper = new EIDHelper();ipEIDHelper.GeometricNetwork = m_ipGeometricNetwork;ipEIDHelper.OutputSpatialReference = ipSpatialReference;ipEIDHelper.ReturnGeometries = true;IEnumEIDInfo ipEnumEIDInfo = ipEIDHelper.CreateEnumEIDInfo(m_ipEnumNetEID_Edges);int count = ipEnumEIDInfo.Count;ipEnumEIDInfo.Reset();for (int i = 0; i < count; i++){string[] info;info = new string[count];ipEIDInfo = ipEnumEIDInfo.Next();ipGeometry = ipEIDInfo.Geometry;ipNewGeometryColl.AddGeometryCollection(ipGeometry as IGeometryCollection);info[i] = m_ipPolyline.Length.ToString();}return m_ipPolyline;}public bool SolvePathGan(string WeightName){try{int intJunctionUserClassID;int intJunctionUserID;int intJunctionUserSubID;int intJunctionID;IPoint ipFoundJunctionPoint;ITraceFlowSolverGEN ipTraceFlowSolver = new TraceFlowSolver() as ITraceFlowSolverGEN;INetSolver ipNetSolver = ipTraceFlowSolver as INetSolver;if (m_ipGeometricNetwork == null){return false;}INetwork ipNetwork = m_work;ipNetSolver.SourceNetwork = ipNetwork;INetElements ipNetElements = ipNetwork as INetElements;if (m_ipPoints == null){ MessageBox.Show("请选择点!!"); return false; }int intCount = m_ipPoints.PointCount;//这里的points 有值吗?////定义一个边线旗数组//*********最近点***************//////////IJunctionFlag[] pJunctionFlagList = new JunctionFlag[intCount];for (int i = 0; i < intCount; i++){INetFlag ipNetFlag = new JunctionFlag() as INetFlag;IPoint ipJunctionPoint = m_ipPoints.get_Point(i);//查找输入点的最近的网络点m_ipPointToEID.GetNearestJunction(ipJunctionPoint, out intJunctionID, out ipFoundJunctionPoint);ipNetElements.QueryIDs(intJunctionID, esriElementType.esriETJunction, out intJunctionUserClassID, out intJunctionUserID, out intJunctionUserSubID);erClassID = intJunctionUserClassID;erID = intJunctionUserID;erSubID = intJunctionUserSubID;IJunctionFlag pTemp = (IJunctionFlag)(ipNetFlag as IJunctionFlag);pJunctionFlagList[i] = pTemp;}ipTraceFlowSolver.PutJunctionOrigins(ref pJunctionFlagList);INetSchema ipNetSchema = ipNetwork as INetSchema;INetWeight ipNetWeight = ipNetSchema.get_WeightByName(WeightName);INetSolverWeights ipNetSolverWeights = ipTraceFlowSolver as INetSolverWeights;ipNetSolverWeights.FromToEdgeWeight = ipNetWeight;//开始边线的权重ipNetSolverWeights.ToFromEdgeWeight = ipNetWeight;//终止边线的权重object[] vaRes = new object[intCount - 1];//通过findpath得到边线和交汇点的集合ipTraceFlowSolver.FindPath(esriFlowMethod.esriFMConnected,esriShortestPathObjFn.esriSPObjFnMinSum,outm_ipEnumNetEID_Junctions, out m_ipEnumNetEID_Edges, intCount - 1, ref vaRes);m_dblPathCost = 0;for (int i = 0; i < vaRes.Length; i++){double m_Va = (double)vaRes[i];m_dblPathCost = m_dblPathCost + m_Va;}m_ipPolyline = null;return true;}catch (Exception ex){Console.WriteLine(ex.Message); return false;}#endregion}private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e){if (clicked != true)return;IPoint ipNew;if (m_ipPoints == null){m_ipPoints = new Multipoint();}ipNew = m_ipActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);object o = Type.Missing;m_ipPoints.AddPoint(ipNew, ref o, ref o);IElement element;ITextElement textelement = new TextElementClass();element = textelement as IElement;clickedcount++;textelement.Text = clickedcount.ToString();element.Geometry = m_ipActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);pGC.AddElement(element, 0);m_ipActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);}3.4实验结果在得到的窗口中加载“甘地的个人地理数据库”(在压缩包中有)中的几何网络“road_Net”,将几何网络地图加载到地图显示窗口中,如下图所示:点击图标添加起始点,效果如下图:然后点击图标,计算最短路径,效果如下图:最后点击图标得到最短路径的缩放,效果如下图:这样就完成了最短路径的查询分析和显示的功能。
数据结构 求图中任意两点最短路径
《数据结构》实验报告◎实验题目: 求最短路径。
◎实验内容:求图中任意两点间的最短路径。
一、需求分析程序目的是求有向图中任意两点间的最短路径。
1、由用户指定图中任意两点。
2、输出结果为指定两点间的最短路径。
二概要设计1、定义结构体typedef struct ArcNode//节点类型{int adjvex;struct ArcNode *nextarc;InfoType_Cost cost;InfoType_Length length;}ArcNode;typedef struct VNode//城市编号{int No;VertexType city[15];ArcNode *firstarc;}VNode,AdjList[MAX_VERTX_NUM];typedef struct ALGraph//图{AdjList vertices;int vexnum;int arcnum;}ALGraph;typedef struct str1{int value_D;int flag_S;}D[20];typedef struct str2{int father;}P[20];2.定义函数void Analyse_Info()操作结果:读入文件,将信息存入数组ALGraph Create_Graph()操作结果:创建一个图void ShortPath_DIJ(ALGraph G,int v_sou)初始条件:已知图G;操作结果:用Dijkstra算法求任意两点之间最短路径。
void InfoCustomer(ALGraph G,str2 p[],str1 d[],int v_sou,int v_des,int method) 操作结果:将最短路径结果呈现给用户。
三详细设计#define INT_MAX 65534#define INFINITY INT_MAX#define MAX_VERTX_NUM 20#define FALSE -1#define TRUE 1typedef char VertexType;typedef int InfoType_Cost;typedef int InfoType_Length;typedef struct ArcNode//节点类型{int adjvex;struct ArcNode *nextarc;InfoType_Cost cost;InfoType_Length length;}ArcNode;typedef struct VNode//城市编号{int No;VertexType city[15];ArcNode *firstarc;}VNode,AdjList[MAX_VERTX_NUM];typedef struct ALGraph{AdjList vertices;int vexnum;int arcnum;}ALGraph;typedef struct str1{int value_D;int flag_S;}D[20];typedef struct str2{int father;}P[20];int arcnum=0,vexnum=0;char city[20][15];int path[52],cost[52];char city_1[52][20],city_2[52][20];P Path_cost,Path_len;D Dear_cost,Dear_len;void Analyse_Info()//读入文件,将信息存入数组{FILE *fp;int i=0,j=0,k=0;int flag_1=0,flag_2=0;int CityCounter=0,LineCounter=0;fp=fopen("data.txt","r");while(!feof(fp)){fscanf(fp,"%s%s %d %d\n",city_1[i],city_2[i],&cost[i],&path[i]);LineCounter++;i++;}arcnum=LineCounter;for(i=0;i<20;){for(k=0;k<52;k++){for (j=0,flag_1=0,flag_2=0;j<=i;j++)//剔除重复出现的城市 {if(strcmp(city[j],city_1[k])==0)flag_1=1;if(strcmp(city[j],city_2[k])==0)flag_2=1;}if(flag_1==0){strcpy(city[i],city_1[k]);CityCounter++;i++;}if(flag_2==0){strcpy(city[i],city_2[k]);CityCounter++;i++;}}if(strlen(city[i])==0) i++;}vexnum=CityCounter;fclose(fp);}ALGraph Create_Graph()//创建图{ALGraph G;int i=0,j,k;ArcNode *p,*q,*e;Analyse_Info();G.arcnum=arcnum;G.vexnum=vexnum;for (i=0;i<20;i++){G.vertices[i].firstarc=(ArcNode*)malloc(sizeof(ArcNode));G.vertices[i].firstarc->nextarc=NULL;}printf("******序号————城市名********\n");for (i=0;i<G.vexnum;i++){G.vertices[i].No=i;strcpy(G.vertices[i].city,city[i]);printf(" %d————%s\n",G.vertices[i].No,G.vertices[i].city);}for (i=0;i<52;i++)for (j=0;j<20;j++)if(strcmp(city[j],city_1[i])==0){for (k=0;k<20;k++)if(strcmp(city[k],city_2[i])==0){p=G.vertices[j].firstarc;while(p!=NULL){q=p;p=p->nextarc;}e=(ArcNode*)malloc(sizeof(ArcNode));e->adjvex=k;e->cost=cost[i];e->length=path[i];e->nextarc=NULL;q->nextarc=e;}}return G;}void ShortPath_DIJ(ALGraph G,int v_sou) //用Dijkstra算法求最短路径{int i,j,no_cost,no_path;int min_cost,min_len;ArcNode *p,*p1,*p2;for (i=0;i<20;i++) //初始化辅助向量{Path_cost[i].father=i;Path_len[i].father=i;}for (i=0;i<20;i++){Dear_cost[i].value_D=INFINITY;Dear_len[i].value_D=INFINITY;Dear_cost[i].flag_S=FALSE;Dear_len[i].flag_S=FALSE;}p=G.vertices[v_sou].firstarc;p=p->nextarc;Dear_len[v_sou].flag_S=TRUE;Dear_cost[v_sou].flag_S=TRUE;while(p){Dear_len[p->adjvex].value_D=p->length;Dear_cost[p->adjvex].value_D=p->cost;Path_len[p->adjvex].father=v_sou;Path_cost[p->adjvex].father=v_sou;p=p->nextarc;}for (i=1;i<G.vexnum;i++)//开始主循环,每次求得v0到某个顶点的最短路径{min_len=INFINITY;min_cost=INFINITY;for (j=0;j<G.vexnum;j++) //找最小的D[j]=min{D[i]}{if( Dear_len[j].value_D<min_len && Dear_len[j].flag_S==FALSE){min_len=Dear_len[j].value_D;no_path=j;}if(Dear_cost[j].value_D<min_cost && Dear_cost[j].flag_S==FALSE){min_cost=Dear_cost[j].value_D;no_cost=j;}}Dear_len[no_path].flag_S=TRUE;Dear_cost[no_cost].flag_S=TRUE;p1=G.vertices[no_path].firstarc;for (p1=p1->nextarc;p1!=NULL;p1=p1->nextarc) //更新{if(Dear_len[p1->adjvex].value_D>(min_len+p1->length)&&Dear_len[p1->adjvex].flag_S==FALSE){Dear_len[p1->adjvex].value_D=min_len+p1->length;Path_len[p1->adjvex].father=no_path;}}p2=G.vertices[no_cost].firstarc;for (p2=p2->nextarc;p2!=NULL;p2=p2->nextarc){if(Dear_cost[p2->adjvex].value_D>(min_cost+p2->cost)&&Dear_cost[p2->adjvex].flag_S==FALSE){Dear_cost[p2->adjvex].value_D=min_cost+p2->cost;Path_cost[p2->adjvex].father=no_cost;}}}}void InfoCustomer(ALGraph G,str2 p[],str1 d[],int v_sou,int v_des,int method)//通知用户所按要求所寻得的最优路径{int i,len=1;int city;char cities[20][15];city=p[v_des].father;strcpy(cities[0],G.vertices[v_des].city);while (city!=v_sou){strcpy(cities[len++],G.vertices[city].city);city=p[city].father;}strcpy(cities[len],G.vertices[v_sou].city);len++;for(i=len-1;i>=0;i--){printf("%s",cities[i]);if(i!=0) printf("-->");}printf("\n");if(method==1){if(d[v_des].value_D==INFINITY) printf("length=%d\n",0);else printf("length=%d\n",d[v_des]);}if(method==2){if(d[v_des].value_D==INFINITY) printf("cost=%d\n",0);else printf("cost=%d\n",d[v_des]);}}四使用说明、测试分析及结果根据提示输入任意两个地点的编号,选择一种权重求最短路径结果如下图所示:。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C源码ArcEngine最短路径分析ArcEngine 最短路径分析(源码)几何网络using System;using ESRI.ArcGIS.Carto;using ESRI.ArcGIS.Geometry;using ESRI.ArcGIS.Geodatabase;using workAnalysis; namespace GisEditor {/// <summary>/// 最短路径分析/// </summary>public class ClsPathFinder{private IGeometricNetwork m_ipGeometricNetwork;private IMap m_ipMap;private IPointCollection m_ipPoints;private IPointToEID m_ipPointToEID;private double m_dblPathCost =0;private IEnumNetEID m_ipEnumNetEID_Junctions;private IEnumNetEID m_ipEnumNetEID_Edges;private IPolyline m_ipPolyline;#region Public Function//返回和设置当前地图public IMap SetOrGetMap{set{ m_ipMap = value;}get{return m_ipMap;}}//打开几何数据集的网络工作空间public void OpenFeatureDatasetNetwork(IFeatureDataset FeatureDa taset){CloseWorkspace();if (!InitializeNetworkAndMap(FeatureDataset))Console.WriteLine( "打开network出错");}//输入点的集合public IPointCollection StopPoints{set{m_ipPoints= value;}get{return m_ipPoints;}}//路径成本public double PathCost{get {return m_dblPathCost;}}//返回路径的几何体public IPolyline PathPolyLine(){IEIDInfo ipEIDInfo;IGeometry ipGeometry;if(m_ipPolyline!=null)return m_ipPolyline;m_ipPolyline = new PolylineClass();IGeometryCollection ipNewGeometryColl = m_ipPolyline as IGeome tryCollection;ISpatialReference ipSpatialReference = m_ipMap.SpatialReferenc e;IEIDHelper ipEIDHelper = new EIDHelperClass();ipEIDHelper.GeometricNetwork = m_ipGeometricNetwork; ipEIDHelper.OutputSpatialReference = ipSpatialReference; ipEIDHelper.ReturnGeometries = true;IEnumEIDInfo ipEnumEIDInfo = ipEIDHelper.CreateEnumEIDInfo(m_i pEnumNetEID_Edges);int count = ipEnumEIDInfo.Count;ipEnumEIDInfo.Reset();for(int i =0;i<count;i++){ipEIDInfo = ipEnumEIDInfo.Next();ipGeometry = ipEIDInfo.Geometry;ipNewGeometryColl.AddGeometryCollection( ipGeometry as IGeometryCollection);}return m_ipPolyline;}//解决路径public void SolvePath(string WeightName){try{int intEdgeUserClassID;int intEdgeUserID;int intEdgeUserSubID;int intEdgeID;IPoint ipFoundEdgePoint;double dblEdgePercent;/*PutEdgeOrigins方法的第二个参数要求是IEdgeFlag类型的数组,* 在VB等其他语言的代码中,只需传人该类型数组的第一个元素即* 可,但C#中的机制有所不同,需要作出如下修改:使用* ITraceFlowSolverGEN替代ITraceFlowSolver*/ITraceFlowSolverGEN ipTraceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN;INetSolver ipNetSolver = ipTraceFlowSolver as INetSolver;INetwork ipNetwork = m_work;ipNetSolver.SourceNetwork = ipNetwork;INetElements ipNetElements = ipNetwork as INetElements;int intCount = m_ipPoints.PointCount;//定义一个边线旗数组IEdgeFlag[] pEdgeFlagList = new EdgeFlagClass[intCount];for(int i = 0;i<intCount ;i++){INetFlag ipNetFlag = new EdgeFlagClass()as INetFlag;IPoint ipEdgePoint = m_ipPoints.get_Point(i);//查找输入点的最近的边线m_ipPointToEID.GetNearestEdge(ipEdgePoint, out intEdgeID,out ipFoundEdgePoint, out dblEdgePercent);ipNetElements.QueryIDs( intEdgeID, esriElementType.esriETEdge, out intEdgeUserClassID, out intEdgeUserID,out intEdgeUserSubI D);erClassID = intEdgeUserClassID;erID = intEdgeUserID;erSubID = intEdgeUserSubID;IEdgeFlag pTemp = (IEdgeFlag)(ipNetFlag as IEdgeFlag); pEdgeFlagList[i]=pTemp;}ipTraceFlowSolver.PutEdgeOrigins(ref pEdgeFlagList); INetSchema ipNetSchema = ipNetwork as INetSchema;INetWeight ipNetWeight = ipNetSchema.get_WeightByName(WeightName);INetSolverWeights ipNetSolverWeights = ipTraceFlowSolver as I NetSolverWeights;ipNetSolverWeights.FromToEdgeWeight = ipNetWeight;//开始边线的权重ipNetSolverWeights.ToFromEdgeWeight = ipNetWeight;//终止边线的权重object [] vaRes =new object[intCount-1];//通过findpath得到边线和交汇点的集合ipTraceFlowSolver.FindPath(esriFlowMethod.esriFMConnected, esriShortestPathObjFn.esriSPObjFnMinSum,out m_ipEnumNetEID_Junctions,out m_ipEnumNetEID_Edges, intCount-1, ref vaRes);//计算元素成本m_dblPathCost = 0;for (int i =0;i<vaRes.Length;i++){double m_Va =(double) vaRes[i];m_dblPathCost = m_dblPathCost + m_Va;}m_ipPolyline = null;}catch(Exception ex){Console.WriteLine(ex.Message);}}#endregion#region Private Function//初始化几何网络和地图private bool InitializeNetworkAndMap(IFeatureDataset FeatureDat aset){IFeatureClassContainer ipFeatureClassContainer;IFeatureClass ipFeatureClass ;IGeoDataset ipGeoDataset;ILayer ipLayer ;IFeatureLayer ipFeatureLayer;IEnvelope ipEnvelope, ipMaxEnvelope ;double dblSearchTol;INetworkCollection ipNetworkCollection = FeatureDataset as INe tworkCollection;int count = ipNetworkCollection.GeometricNetworkCount;//获取第一个几何网络工作空间m_ipGeometricNetwork = ipNetworkCollection.get_GeometricNetwor k(0);INetwork ipNetwork = m_work;if(m_ipMap!=null){m_ipMap = new MapClass();ipFeatureClassContainer = m_ipGeometricNetwork as IFeatureCla ssContainer;count = ipFeatureClassContainer.ClassCount;for(int i =0;i<count;i++){ipFeatureClass = ipFeatureClassContainer.get_Class(i); ipFeatureLayer = new FeatureLayerClass();ipFeatureLayer.FeatureClass = ipFeatureClass;m_ipMap.AddLayer( ipFeatureLayer);}}count = m_yerCount;ipMaxEnvelope = new EnvelopeClass();for(int i =0;i<count;i++){ipLayer = m_ipMap.get_Layer(i);ipFeatureLayer = ipLayer as IFeatureLayer;ipGeoDataset = ipFeatureLayer as IGeoDataset;ipEnvelope = ipGeoDataset.Extent;ipMaxEnvelope.Union( ipEnvelope);}m_ipPointToEID = new PointToEIDClass();m_ipPointToEID.SourceMap = m_ipMap;m_ipPointToEID.GeometricNetwork = m_ipGeometricNetwork;double dblWidth = ipMaxEnvelope.Width; double dblHeight = ipMaxEnvelope.Height;if( dblWidth > dblHeight)dblSearchTol = dblWidth / 100;elsedblSearchTol = dblHeight / 100;m_ipPointToEID.SnapTolerance = dblSearchTol; return true ;}//关闭工作空间private void CloseWorkspace(){m_ipGeometricNetwork = null;m_ipPoints = null;m_ipPointToEID = null;m_ipEnumNetEID_Junctions = null;m_ipEnumNetEID_Edges = null;m_ipPolyline = null;}#endregion}}备注:在调用该类时的次序:ClsPathFinder m_ipPathFinder;if(m_ipPathFinder==null)//打开几何网络工作空间{m_ipPathFinder = new ClsPathFinder();ipMap = this.m_ActiveView.FocusMap;ipLayer = ipMap.get_Layer(0);ipFeatureLayer = ipLayer as IFeatureLayer;ipFDB = ipFeatureLayer.FeatureClass.FeatureDataset;m_ipPathFinder.SetOrGetMap = ipMap;m_ipPathFinder.OpenFeatureDatasetNetwork(ipFDB);}private void ViewMap_OnMouseDown(object sender, ESRI.ArcGIS.MapCon trol.IMapControlEvents2_OnMouseDownEvent e)//获取地图上鼠标输入的点{IPoint ipNew ;if( m_ipPoints==null){m_ipPoints = new MultipointClass();m_ipPathFinder.StopPoints = m_ipPoints;}ipNew = ViewMap.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x,e.y);object o = Type.Missing;m_ipPoints.AddPoint(ipNew,ref o,ref o);}m_ipPathFinder.SolvePath("Weight");//先解析路径IPolyline ipPolyResult = m_ipPathFinder.PathPolyLine();//最后返回最短路径网络数据集的最短路径这里的添加出发点或者目的点,是往“Facilities”或“Incidents”图层上添加元素。