Breadth first recursion

In computer programming, Breadth first recursion is one of design patternss.

Problem: Find routes to everything, or find the shortest route there.

Solution: Maintain a queue of items to examine. When you find something you need to recurse into, put it on the end of the queue. Keep a list of things you've already done so you know what you do and don't need to recurse into.

Concepts of depth first and breadth first are confusing. First attempts at writing code to traverse a map, directory structure, and so forth, mix elements of both unsuccessfully.

 sub solve_maze {
 
   my $me = $_[0];
   my $dest = $_[1];
 
   return ($me) if $me eq $dest;
 
   my @queue = ($me);
   my %route = ($me => [$me]); 
 
   while(my $ob = shift @queue) {
 
     foreach my $i (@{$ob->neighbors()}) {
 
       if(!$route{$i}) {
         $route{$i} = [ @{$route{$ob}}, $i ];
         return \\$route{$i} if($i eq $dest);
         push @queue, $i;
       }       
 
     }
   } 
 }
 
Objects represent blocks on a map. Each object returns a list of neighbors when the //->neighbors()// method is called.

//@queue// is the list of directions we haven't taken yet, and need to get back to. We do them in the order found. When going through a directory structure on a filesystem, that would do the top level directories first, then the 2nd level ones, then the 3rd level, and so forth.

//%route// keeps track of what we've found, and how we've found it. Every node we find, we know the path to: the path to the current node plus the current neighbor we're examining. Initially, the current node is the root node, and all of its neighbors will have a two hop path: the root node, then the current neighbor. This pattern repeats for all of their neighbors.

For our purposes, we want to know the route used to get from one place to another: we return a list of steps taken to get there. We want the first match. There may be several paths. Removing the //return \\$route...// line will find all of the routes, shortist routes first, without duplicates. Before the //if(!$route...// line, instead put:

 push @routes_to_dest, [ @{$route{$ob}}, $i ] if($i eq $dest);

That will log all routes we find, not merely the first.

Since BreadthFirst recurssion starts at the root and expands outward in all directions at the same rate, it is optimal for cases where the target and destination are near by.

DepthFirst recurssion is even easier to implement, and is optimal for cases where every node must be visited. It goes as far as it can in any one direction, then goes back until it finds another route. Since new tangets are taken as soon as they are found, there is no need to remember what has been done or what needs to be done - only where you were on previous routes when you took a tangent.

External Links

The article is originally from Perl Design Patterns Book.


See also
  • DepthFirst


In the News

Palaeography: Reading Old Handwriting, 1500-1800: A Practical Online T
"Palaeography is the study of old handwriting. This web tutorial will help you learn to read the handwriting found in documents written in English between 1500 and 1800."Practice documents include wills, petitions, estate inventories, and fun material such as "Recipe for mince pies. Early 17th century."From the National Archives (Surrey, United Kingdom) in partnership with University College London.

[Ironic] An Italian pensioner committed suicide after his wife fell in
Recalling the end of Romeo and Juliet, the 70-year-old man, Ettore, who had sat by his wife's bedside for four months after she slipped into a coma following a heart attack, finally gave up hope and gassed himself in the garage of his family home.Less than a day later, his wife, Rossana, woke up in her hospital bed in Padua and immediately asked for him.

New Inherited Disease Can Cause Early Aortic Rupture
Researchers have identified a new inherited syndrome that can cause the heart's aorta to rupture earlier than other aortic aneurysm syndromes, such as Marfan syndrome. They said the newly identified syndrome is a relatively common disorder, which can be corrected with surgery if it is diagnosed early.

Private Warriors
This Public Broadcasting Service (PBS) Frontline program looks "at private contractors servicing U.S. military supply lines, running U.S. military bases, and protecting U.S. diplomats and generals"in Kuwait and Iraq. Website features discussions of the appropriateness of outsourcing, whether privatization saves taxpayer money, and the role of contractors. Includes contractor profiles, interviews, a FAQ, video of the program, and related links.

Endoscopic Sinus Surgery Is Safe, Effective In Older Patients
Minimally invasive surgery to alleviate the pain and pressure of sinusitis is a safe, effective therapy for geriatric patients who can't be helped by medication alone, according to new research.

BSE (Bovine Spongiform Encephalopathy, or Mad Cow Disease)
Contains information on control measures and reported cases, as well as news and articles on BSE. Includes links to information on related diseases. From the Centers for Disease Control and Prevention, U.S. Department of Health and Human Services.

Wnt Signaling Controls The Fate Of Stem Cells In Adult Brains
Scientists at the Salk Institute for Biological Studies have identified a crucial cellular signal that controls the fate of stem cells in the brains of adult mice.

After Insects Attack, Plants Bunker Sugars For Later Regrowth
Using radioactive carbon and genetically modified native tobacco plants, Max Planck Society scientists and colleagues have discovered the first gene mediating tolerance to herbivore attack.

Easing Children's Pain During Medical Procedures
A new system under development will help children better cope with pain during difficult medical procedures. The system works by using a Web-based software to advise nurses on the best way to distract children from the procedures that cause the pain. The distractions could be anything from having a book read to them, watching a video, talking, or playing a game.

Mosquito Spray Increases Toxicity Of Existing Pesticides In The Enviro
A relatively benign compound contained in a widely used group of insecticides can mix with and increase the toxicity of existing pesticides in the environment, according to a new study led by UC Berkeley biologists. Based upon these findings, regulators should not only consider the toxicity of individual active ingredients in a product, but also how ingredients may interact with other chemicals in the environment, the researchers said.


MP3 Music Downloads

Preview songs, Download Free Music,Burn CDs at ITunes.com
iTunes_RGB_9mm

 


Google




InformationQuickFind.com - Find Information Fast

Links