最短路:
单源最短路(确定起点和终点):所有边权都是正
多源最短路(多个)
稀疏:领接表
稠密:邻接矩阵
Dijkstra朴素算法
注意:
数据结构:
N-边缘值
g[][]-邻接矩阵
st[]-状态,访问1,未访问0
d[i]-从1号点到i号点的距离
package 大学菜;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Dijkstra求最短路径2 {
//数据结构
static int N=10010;
static int[][] g = new int[N][N];
static int[] d = new int[N];
static boolean[] st = new boolean[N];
static int n,m;
public static int Dijkstra(){
//初始化d
Arrays.fill(d,0x3f3f);
d[1] = 0;
for(int i=1;i<=n;i++){//n个点
int t=-1;
for(int j=1;j<=n;j++){
if(!st[j] && (t==-1||d[t]>d[j])){
//当前t
t=j;
}
}
//说明这个t点找到列
st[t] = true;
//更新
for(int j=1;j<=n;j++){
d[j] = Math.min(d[j],d[t]+g[t][j]);
}
}
if(d[n] == 0x3f3f) return -1;
return d[n];
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] s = reader.readLine().split(" ");
n = Integer.valueOf(s[0]);//行
m = Integer.valueOf(s[1]);//列
//先给g赋值,赋为无穷
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
g[i][j] = 0x3f3f;
}
}
//接收
for(int i=0;i<m;i++){
String[] ss = reader.readLine().split(" ");
int x = Integer.valueOf(ss[0]);
int y = Integer.valueOf(ss[1]);
int z = Integer.valueOf(ss[2]);
g[x][y] = Math.min(g[x][y],z);
}
System.out.println(Dijkstra());
}
}
堆优化像宽搜
bellman-不能有负值回路
1.有限制边-使用bellman
如果有负环的话,就可以把路径值编程负无穷
spfa-没有负环,一般没有
优化后面的数组
队列存的是等待更新的点。
队列放的是刚进去的边
判读有没有负环-
判断条件:
cunt(x)>=n
floed
领结矩阵存储图-d[i][j]
从i点出发,只经过1-k这些点到达j的最短距离