只要我们的题给的是无向图我们就可以用这个来解:
shortest[] : 最短路数组,我们这个数组中放的是源结点到图中其他点的最短路径,下标对应点(初始化的时候 起点的位置要标记为0,其他位置标记为Integer.MaxValue/2)
source :起点(源结点)
ArrayList<Edge>:我们使用一个线性集合来存储我们的边
类Edge:里面放变量起点,终点,权值;众所周知!!!!两点确定一条边。
class Edge{
int from;
int to;
int value;
public Edge(int from , int to ,int value) {
this.from = from;
this.to = to;
this.value = value;
}
}
输入的时候把我们的边都存入到ArrayList类中
然后通过一个结点循环套边循环,找出源点到每一个结点的距离
我们以牛客网的单源最短路径为例子来看:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int 顶点数
* @param m int 边数
* @param graph int二维数组 一维3个数据,表示顶点到另外一个顶点的边长度是多少
* @return int
*/
static int[] shortest;
public int findShortestPath (int n, int m, int[][] graph) {
ArrayList<Edge> list = new ArrayList<>();
shortest = new int[n+1];
Arrays.fill(shortest, Integer.MAX_VALUE/2);
shortest[1] = 0;
for(int i = 0;i<m;i++) {
int from = graph[i][0];
int to = graph[i][1];
int value = graph[i][2];
list.add(new Edge(from,to,value));
}
for(int i = 1;i<=n;i++) {
for(Edge edge : list) {
int from = edge.from;
int to = edge.to;
int value = edge.value;
shortest[to] = Math.min(shortest[to], shortest[from]+value);
}
}
return shortest[n];
}
}
class Edge{
int from;
int to;
int value;
public Edge(int from , int to ,int value) {
this.from = from;
this.to = to;
this.value = value;
}
}
其中,最关键的代码
shortest[to] = Math.min(shortest[to], shortest[from]+value);
上图: