I was doing this question http://www.spoj.com/problems/SHOP/ .The question boils down to calculating shortest path between 2 points in a weighted graph where verticecs have weights.i implemented a working solution using bfs https://code.hackerearth.com/ff00c2Z, it works fine on sample test cases but gives WA verdict ,when i googled some solutions i saw that the actual solution uses dijkstra .when i tried to find my mistake i saw that i had used deque instead of priority queue what difference does it makes in this case ?why deque is not working ? is my approach wrong ? then how can this problem be done using BFS?
You are using deque
instead of priority queue
and you are asking what is wrong?
First of all in dequeue
you have not prioritized things here based on distance. The first enqueued object or last enqueued object is always given the highest preference but it might be the case that a middle element should have highest priority (it might become a highest priority object) That's why you are getting WA.
Note: I have just stated the pre-condition for using dijkstra. You can also solve this problem using BFS
and also using Dijkstra
.
Note 2: Use data structure when needed. You don't need deque in BFS just use a queue and that will suffice otherwise it becomes more complex to handle for large code.