单源最短路径问题2 (Dijkstra算法)
用邻接矩阵
/* 单源最短路径问题2 (Dijkstra算法) 样例: 5 7 0 1 3 0 3 7 1 2 4 1 3 2 2 3 5 2 4 6 3 4 4 输出: [0, 3, 7, 5, 9] */ import java.util.Arrays; import java.util.Scanner; public class Main { //图的顶点数,总边数 static int V, E; //存储所有的边,大小为顶点数 static int[][] Edges; static int[] d; static boolean[] visited; static final int MAX_VALUE = 999999; public static void main(String[] args) { creatGraph(); shortPath(1); System.out.println(Arrays.toString(d)); } static void shortPath(int start) { d = new int[V]; visited = new boolean[V]; Arrays.fill(d, MAX_VALUE); d[start] = 0; while (true) { int min_index = -1; for (int j = 0; j < V; j++) { if (!visited[j] && (min_index == -1 || d[j] < d[min_index])) { min_index = j; } } if (min_index == -1) break; visited[min_index] = true; for (int u = 0; u < V; u++) { d[u] = Math.min(d[u], d[min_index] + Edges[min_index][u]); } } } static void creatGraph() { Scanner sc = new Scanner(System.in); V = sc.nextInt(); E = sc.nextInt(); Edges = new int[V][V]; for (int[] i : Edges) Arrays.fill(i, MAX_VALUE); for (int i = 0; i < E; i++) { int u = sc.nextInt(); int v = sc.nextInt(); int w = sc.nextInt(); Edges[u][v] = w; Edges[v][u] = w; } } }
用邻接表
/* 单源最短路径问题2 (Dijkstra算法) 样例: 5 7 0 1 3 0 3 7 1 2 4 1 3 2 2 3 5 2 4 6 3 4 4 输出: [0, 3, 7, 5, 9] */ import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { //图的顶点数,总边数 static int V, E; //存储所有的边,大小为顶点数 static ArrayList<Edge>[] Edges; static int[] d; static boolean[] visited; static final int MAX_VALUE = 999999; public static void main(String[] args) { creatGraph(); shortPath(1); System.out.println(Arrays.toString(d)); } static void shortPath(int start) { d = new int[V]; visited = new boolean[V]; Arrays.fill(d, MAX_VALUE); d[start] = 0; while (true) { int min_index = -1; for (int j = 0; j < V; j++) { if (!visited[j] && (min_index == -1 || d[j] < d[min_index])) { min_index = j; } } if (min_index == -1) break; visited[min_index] = true; for (Edge i : Edges[min_index]) { d[i.to] = Math.min(d[i.to], d[min_index] + i.cost); } } } static void creatGraph() { Scanner sc = new Scanner(System.in); V = sc.nextInt(); E = sc.nextInt(); Edges = new ArrayList[V]; for (int i = 0; i < V; i++) Edges[i] = new ArrayList(); for (int i = 0; i < E; i++) { int u = sc.nextInt(); int v = sc.nextInt(); int w = sc.nextInt(); Edges[u].add(new Edge(v, w)); Edges[v].add(new Edge(u, w)); } } } class Edge { int to; int cost; public Edge(int to, int cost) { this.to = to; this.cost = cost; } }