简体   繁体   中英

Dynamic queue for implementing Breadth-First algorithm efficiently

I am in the midst of constructing a Breadth-First graph searching algorithm, for searching the London Underground.

I have the algorithm figured out but as you may well know, the algorithm requires a Queue ADS in order to track all of the edges that need searching (in the correct order).

I have been reading about efficiency issues to do with managing the queue and a large or very large number of queued items (edges).

Can anyone please tell me how to implement a queue based around the Java ArrayList, that can track head and tail and that manages the memory effectively while it's growing?

Any tips/pointers much appreciated!!

I think your question is closely related to this topic: Breadth-First search in Java

Don't use ArrayList unless you have a really good reason. Java already comes with a great set of queue implementations -- see the Queue interface for details.

In your case, it might suffice to pick LinkedList as your queue implementation. See also http://www.codeproject.com/KB/java/BFSDFS.aspx for an easy to follow example of a breadth first search implementation that uses LinkedList as a queue.

Keep in mind you're going to want a fast test to see whether your object is already in the queue or not. Neither ArrayList nor Queue provide this functionality (their contains check is O(n) ). If you can modify the objects you are dealing with by adding an extra field, then it is easy. If not, you'll want to maintain some sort of fast Set (a HashSet , probably) to keep track of which objects are in the queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM