I was solving BFS
problem. I used PriorityQueue but I was getting wrong answer, then I used LinkedList
, I got right ans. I'm unable to find the difference between them. Here are both the codes. Why both the answers are different?
Code1:
LinkedList q=new LinkedList();
q.add(src);
dist[src]=0;
visited[src]=1;
while(!q.isEmpty()){
u=(int)(Integer) q.remove(0);
for (int k = 0; k < n; k++) {
if(a[u][k]==1 && visited[k]==0)
{
dist[k]=dist[u]+1;
q.add(k);
visited[k]=1;
}
}
}
Code 2:
PriorityQueue<Integer> q= new PriorityQueue<>();
q.add(src);
dist[src]=0;
visited[src]=1;
while(!q.isEmpty()){
u=q.remove();
for (int k = 0; k < n; k++) {
if(a[u][k]==1 && visited[k]==0)
{
dist[k]=dist[u]+1;
q.add(k);
visited[k]=1;
}
}
}
Also when I used Adjacency List instead of Adjacency matrix, Priority Queue implementation gave right ans.