public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int source= sc.nextInt();
int dest = sc.nextInt();
int noOfVertices= sc.nextInt();
int noofEdges= sc.nextInt();
int GreeLights[] = new int[noOfVertices+1];
HashMap<edge, Integer> edgeInfo= new HashMap<>();
Graph g= new Graph();
for(int i=1;i<=noOfVertices;i++){
GreeLights[i]=sc.nextInt();
}
for(int i=1;i<=noofEdges;i++){
int x= sc.nextInt();
int y= sc.nextInt();
int weight= sc.nextInt();
edge e= new edge(x,y);
edgeInfo.put(e, weight);
g.adj.put(x, new LinkedList<Integer>());
g.addNeighbour(x, y);
}
boolean visited[]= new boolean[noOfVertices+1];
int distance[]= new int[noOfVertices+1];
for(int i=1;i<=noOfVertices;i++){
visited[i]=false;
distance[i]=1000;
}
distance[source]=0;
for(int i=1;i<=noOfVertices;i++){
int min=1000;
int minIndex=-1;
for(int j=1;j<=noOfVertices;j++){
if(distance[j]<min){
min=distance[j];
minIndex=j;
}
}
visited[minIndex]=true;
LinkedList<Integer> LL= g.getNeighbors(minIndex);
for(int x:LL){
if(visited[x]!=true){
edge e = new edge(minIndex,x);
int weightofEdge=edgeInfo.get(e); //Null pointer exception occuring here
int distancetoNeighbour =
distance[minIndex]+weightofEdge;
if(distance[x]>distancetoNeighbour){
int greenTime=GreeLights[x];
int wait=0;
for(int j=0;j<distancetoNeighbour;){
j=j+greenTime;
wait=j;
}
wait-=distancetoNeighbour;
if(wait==0){
distance[x]=distancetoNeighbour;
}
else{
distance[x]=distancetoNeighbour+wait;
}
}
}
}
}
System.out.println(distance[dest]);
}
我創建了一個散列表,將邊緣存儲爲鍵,並將該邊的權值存儲爲值。現在應用Dijkstras算法來解決我需要得到與邊相對應的權值的問題。所以我創建了一個新的邊,其頂點與hashmap中存在的所需邊相同,但是當我調用edgeInfo.get()函數來獲取該邊的權值時,它會顯示NullPointerException ...任何人都可以幫助我...空指針異常
我的邊緣種類是: -
class edge{
int x;
int y;
public edge(int x,int y){
this.x=x;
this.y=y;
}
public boolean equals(edge e){
return (this.x==e.x && this.y==e.y);
}
}
提的編程語言將是很好的返回值。 – JJJ
對不起兄弟我的錯 –
什麼是堆棧跟蹤? –