Java Prims算法到Dijkstra算法
我正在尝试使我现有的Prim算法实现保持与源的跟踪距离。因为prim和Dijkstra的算法几乎相同。我不知道我在哪里遗漏了什么 我知道问题出在哪里,但无法解决 这是我的代码,如何修改它以打印从源到所有其他顶点的最短距离。最短距离存储在名为:dist[]的数组中 代码:Java Prims算法到Dijkstra算法,java,algorithm,Java,Algorithm,我正在尝试使我现有的Prim算法实现保持与源的跟踪距离。因为prim和Dijkstra的算法几乎相同。我不知道我在哪里遗漏了什么 我知道问题出在哪里,但无法解决 这是我的代码,如何修改它以打印从源到所有其他顶点的最短距离。最短距离存储在名为:dist[]的数组中 代码: 包图; 导入java.util.ArrayList; 公共类Prims{ 静态int no_of_顶点=0; 公共静态void main(字符串[]args){ int[][]图={{0,2,0,6,0}, {2, 0, 3,
包图;
导入java.util.ArrayList;
公共类Prims{
静态int no_of_顶点=0;
公共静态void main(字符串[]args){
int[][]图={{0,2,0,6,0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
};
顶点的数量=graph.length;
int[][]结果=新的int[没有顶点][没有顶点];
boolean[]访问=新的boolean[no_of_顶点];
int dist[]=新int[没有顶点];
for(int i=0;i图形[i][j]){
min=图[i][j];
dist[i]+=min;//for(int j=0;j图形[i][j]){
min=图[i][j];
距离[i]+=min//
package Graphs;
import java.util.ArrayList;
public class Prims {
static int no_of_vertices = 0;
public static void main(String[] args) {
int[][] graph = {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
};
no_of_vertices = graph.length;
int [][] result = new int [no_of_vertices][no_of_vertices];
boolean[] visited = new boolean[no_of_vertices];
int dist[] = new int[no_of_vertices];
for (int i = 0; i < no_of_vertices; i++)
for (int j = 0; j < no_of_vertices; j++) {
result[i][j]= 0;
if (graph[i][j] == 0) {
graph[i][j] = Integer.MAX_VALUE;
}
}
for (int i = 0; i < no_of_vertices; i++) {
visited[i] = false;
dist[i] = 0;
}
ArrayList<String> arr = new ArrayList<String>();
int min;
visited[0] = true;
int counter = 0;
while (counter < no_of_vertices - 1) {
min = 999;
for (int i = 0; i < no_of_vertices; i++) {
if (visited[i] == true) {
for (int j = 0; j < no_of_vertices; j++) {
if (!visited[j] && min > graph[i][j]) {
min = graph[i][j];
dist[i] += min; // <------ Problem here
visited[j] = true;
arr.add("Src :" + i + " Destination : " + j
+ " Weight : " + min);
}
}
}
}
counter++;
}
for (int i = 0; i < no_of_vertices; i++) {
System.out.println("Source : 0" + " Destination : " + i
+ " distance : " + dist[i]);
}
for (String str : arr) {
System.out.println(str);
}
}
}
for (int j = 0; j < no_of_vertices; j++) {
if (!visited[j] && min > graph[i][j]) {
min = graph[i][j];
dist[i] += min; // <------ Problem here
if (dist[i] + graph[i][j] < dist[j])
dist[j] = dist[i] + graph[i][j];