文章标题
来源:互联网 发布:纱线捻度机数据含义 编辑:程序博客网 时间:2024/05/11 18:44
迪杰斯特拉算法求最短路径问题(java实现)
算法思想:先定义一个二维数组将每个顶点到其余直接相连顶点的距离保存起来,若没有直接相连,则用Integer.MAX_VALUE(int类型的最大值)代替,再定义两个一位数组distance[],previous[],distance用来保存某个顶点到其余顶点的最短距离,previous则保存其余顶点的前驱顶点的下标,通过主次比较筛选出最短路径。
代码实现:
public class ShortestPath {
private static int max = Integer.MAX_VALUE;
private static int[] dist = new int[6];
private static int[] prev = new int[6];
private static int a[][]={
{0,max,10,max,30,100},
{max,0,5,max,max,max},
{max,max,0,50,max,max},
{max,max,max,0,max,10},
{max,max,max,20,0,60},
{max,max,max,max,max,0}
};
public static void main(String[] args) {
// TODO Auto-generated method stub ShortestPath shortestPath = new ShortestPath(); shortestPath.dijkstra(0, a, dist, prev); System.out.print("顶点0到其余顶点的最短路径是:"); for(int i = 0;i < dist.length;i++){ System.out.print(dist[i]+" "); } //System.out.println("hehe");}/** * 迪杰斯特拉算法 */public void dijkstra(int v,int[][] a,int[] dist,int[] prev){ int n = dist.length - 1; boolean[] s = new boolean[n+1];//判断该顶点是否找到了最短路径 for(int i = 1;i <= n;i++){ //初始化dist数组 dist[i] = a[v][i]; s[i] = false; if(dist[i] < max){ prev[i] = v; }else{ prev[i] = -1; } } dist[v] = 0; s[v] = true; for(int i = 1;i <= n;i++){ int temp = Integer.MAX_VALUE;//temp暂存v到其余定点的最短距离 int u = v; for(int j = 1;j <= n;j++){ if((!s[j]) && dist[j] < temp){//如果该顶点不属于s顶点集并且该顶点有前驱顶点 u = j;//更新当前源顶点,将 temp = dist[j];//更新当前最短路径 } } s[u] = true; for(int j = 0;j <= n;j++){ if((!s[j]) &&a[u][j] < max){ int newDist = dist[u] + a[u][j]; if(newDist < dist[j]){ dist[j] = newDist; prev[j] = u; } } } } }
}
0 0
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- TortoiseSVN,TortoiseGit修改差异查看器为BeyondCompare
- webview 上 postUrl 发送参数过程中数据丢失或错误 的问题
- 积分图的概念、计算及代码
- Spring定时任务的几种实现
- UFT 12破解&无限试用
- 文章标题
- textField 和 按钮
- Java 开源博客 Solo 1.2.0 发布 - 一键启动
- android studio开发环境配置(指定SDK及卸载)附安装文件网盘地址(win7 64位)
- 对chain.doFilter(request,response)的理解
- 开启mysql事件
- IDEA15创建maven web项目基础
- 安装nginx
- leetcode--Valid Palindrome--- 算法简单,需要看看怎么写的