我正在努力实现Dijkstra,也在学习Streams.我不能使用流实现下面的代码片段.我正在try 使用STREAMS迭代映射、根据 node 筛选键并更新dist数组,所有这些都在一行中完成.
input adj=[[2,1,1],[2,3,1],[3,4,1]]
n=4
S(Source)=2
class Pair{
int node;
int weight;
public Pair(int weight,int node) {
this.node=node;
this.weight=weight;
}
}
class Solution {
public int dijkstra(int[][] adj, int n, int S) {
int [] dist=new int[n];
Arrays.fill(dist,(int)1e9);
Map <Integer,List<Pair>> dic;
dic=new HashMap<>();
for(int i=0;i<adj.length;i++) {
int nd=(int)adj[i][1];
int wt=(int)adj[i][2];
Pair p=new Pair(wt,nd);
dic.computeIfAbsent((int)adj[i][0],y->new LinkedList<Pair>()).add(p);
}
PriorityQueue <Pair>pq=new PriorityQueue<>((x,y)->x.weight-y.weight);
dist[k-1]=0;
pq.add(new Pair(0,S));
while(pq.size() > 0) {
int dis=pq.peek().weight;
int node=pq.peek().node;
pq.remove();
// How to implement the below code using Streams in one line
------------------------------------------------
dic.entrySet().stream()
.filter(e->e.getKey().equals(node))
.filter(entry -> entry.getValue()
.forEach(p->{
if(dis+p.weight<dist[p.node-1]){
dist[p.node-1]=dis+p.weight;
pq.add(new Pair(dis+p.weight,p.node));
}
}));
}
}
}
```