我试图解决HackerRank上的一个问题,我已经尝试解决它,我发现它给出的距离像-2149088,虽然我的逻辑最重要的是在while循环中存在问题。指出我的错误即时通讯:)谢谢。链接到问题陈述HackerRank:https://www.hackerrank.com/challenges/dijkstrashortreach
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int cases = in.nextInt();
for(int i=0; i<cases; i++){
int N = in.nextInt();
int M = in.nextInt();
int adj[][] = new int[N+1][N+1];
Node nodes[] = new Node[N+1];
for(int k=1; k<=N; k++)
nodes[k] = new Node(k);
for(int j=0; j<=N; j++)
for(int k=0; k<=N; k++)
adj[j][k] = Integer.MAX_VALUE;
for(int j=0; j<M; j++){
int A = in.nextInt();
int B = in.nextInt();
int W = in.nextInt();
adj[A][B] = Math.min(W,adj[A][B]);
adj[B][A] = Math.min(W,adj[A][B]);
}
int S = in.nextInt();
nodes[S].dist = 0;
PriorityQueue<Node> que = new PriorityQueue<Node>();
for(int k=1; k<=N; k++)
que.add(nodes[k]);
while(!que.isEmpty()){
Node q = que.poll();
int id = q.ID;
for(int j=1; j<=N; j++){
if(adj[id][j] != Integer.MAX_VALUE){
System.out.println(""+q.dist);
if(nodes[j].dist>q.dist+adj[id][j]){
nodes[j].dist = q.dist+adj[id][j];
}
}
}
}
for(int j=1; j<=N; j++){
if(nodes[j].dist==Integer.MAX_VALUE){System.out.println("-1");}
else if(nodes[j].dist!=0) {System.out.print(nodes[j].dist+" ");}
}
}
}
}
class Node implements Comparable<Node>{
public int dist;
public int ID;
public Node(int getID){
this.ID = getID;
dist = Integer.MAX_VALUE;
}
@Override
public int compareTo (Node node) {
return Integer.valueOf(this.dist).compareTo(node.dist);
}
}
答案 0 :(得分:0)
如果您将dist设置为Integer.MAX_VALUE,然后在此处进行检查:
if(nodes[j].dist>q.dist+adj[id][j]){
nodes[j].dist = q.dist+adj[id][j];
}
然后节点[j] .dist总是大于q.dist + adj [id] [j],因为MAX_VALUE + adj [id] [j]&lt;你有一个整数溢出并将溢出的值赋给节点[j] .dist。
我希望它有所帮助。