faif
BreadthFirst.h
1 #ifndef FAIF_BREADTH_FIRST_SEARCH_HPP
2 #define FAIF_BREADTH_FIRST_SEARCH_HPP
3 
4 #include <vector>
5 #include <queue>
6 #include <deque>
7 #include <algorithm>
8 
9 #include "TreeNodeImpl.hpp"
10 
11 #include <iostream>
12 using namespace std;
13 
14 
15 namespace faif {
16  namespace search {
17 
18  /**
19  @brief The breadth-first search algorithm
20 
21 
22  from starting state the function build the tree structure,
23  explores all the nearest nodes (children), and if it not find the goal generates
24  the nearest nodes to the children.
25  The return is the shortest path from root node to the goal node.
26  Function is protected against the cycles in the graph.
27  The maximum depth of tree is limited.
28  */
29  template<typename T>
30  typename Node<T>::Path searchBreadthFirst(boost::shared_ptr<T> start, int max = 200) {
31  //the methods to create tree-like structures are required
32  BOOST_CONCEPT_ASSERT((NodeWithChildrenConcept<T>));
33  BOOST_CONCEPT_ASSERT((NodeWithFinalFlagConcept<T>));
34 
35  std::queue< TreeNode<T>* > buffer;
36 
37  TreeNode<T> root(start);
38  TreeNode<T>* curr = &root;
39 
40  buffer.push(&root);
41 
42  while (!buffer.empty()) {
43 
44  curr = buffer.front();
45  buffer.pop();
46 
47  // cout << "Buffer size " << buffer.size() << " curr " << endl << *curr->getPoint() << endl;
48 
49  //check if the node is twice on the path from node to root
50  if ( checkNodeInPath( *curr ) )
51  continue;
52 
53  //check if the node is the final node
54  if (curr->getPoint()->isFinal() )
55  break;
56 
57  //check if the maximum depth
58  if (curr->getLevel() == max)
59  continue;
60 
61  typename TreeNode<T>::Children ch = curr->getChildren();
62  for( typename TreeNode<T>::Children::const_iterator it = ch.begin(); it != ch.end(); ++it )
63  buffer.push( *it );
64  }
65 
66  typename Node<T>::Path path;
67 
68  if (curr->getPoint()->isFinal() )
69  path = curr->generatePathToRoot();
70 
71  return path;
72  }
73 
74 
75  } //namespace search
76 } //namespace faif
77 
78 #endif //FAIF_BREADTH_FIRST_SEARCH_HPP
79 
Definition: Chain.h:17
the concept for node with children
Definition: Node.hpp:44
STL namespace.
boost::shared_ptr< T > getPoint() const
Definition: TreeNodeImpl.hpp:45
the struct to create node in search space from individual
Definition: Node.hpp:26
Node< T >::Path searchBreadthFirst(boost::shared_ptr< T > start, int max=200)
The breadth-first search algorithm.
Definition: BreadthFirst.h:30
the template to create the node in tree-based search methods
Definition: TreeNodeImpl.hpp:17
the concept for node with final flag for search in tree-like structures The function &#39;searchDepthFirs...
Definition: Node.hpp:60
Children getChildren()
Definition: TreeNodeImpl.hpp:95
Node< T >::Path generatePathToRoot() const
Definition: TreeNodeImpl.hpp:135
short getLevel() const
Definition: TreeNodeImpl.hpp:61
bool checkNodeInPath(const TreeNode< T > &n)
Definition: TreeNodeImpl.hpp:82