COIN-OR::LEMON - Graph Library

source: lemon/lemon/bfs.h @ 1258:bdfc038f364c

Last change on this file since 1258:bdfc038f364c was 1125:b873350e6258, checked in by Alpar Juttner <alpar@…>, 12 years ago

Intel C++ compatibility fixes

File size: 54.3 KB
RevLine 
[209]1/* -*- mode: C++; indent-tabs-mode: nil; -*-
[100]2 *
[209]3 * This file is a part of LEMON, a generic C++ optimization library.
[100]4 *
[463]5 * Copyright (C) 2003-2009
[100]6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
12 *
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_BFS_H
20#define LEMON_BFS_H
21
22///\ingroup search
23///\file
[244]24///\brief BFS algorithm.
[100]25
26#include <lemon/list_graph.h>
27#include <lemon/bits/path_dump.h>
[220]28#include <lemon/core.h>
[100]29#include <lemon/error.h>
30#include <lemon/maps.h>
[278]31#include <lemon/path.h>
[100]32
33namespace lemon {
34
35  ///Default traits class of Bfs class.
36
37  ///Default traits class of Bfs class.
[157]38  ///\tparam GR Digraph type.
[100]39  template<class GR>
40  struct BfsDefaultTraits
41  {
[244]42    ///The type of the digraph the algorithm runs on.
[100]43    typedef GR Digraph;
[244]44
45    ///\brief The type of the map that stores the predecessor
[100]46    ///arcs of the shortest paths.
[209]47    ///
[244]48    ///The type of the map that stores the predecessor
[100]49    ///arcs of the shortest paths.
50    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[244]51    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
[525]52    ///Instantiates a \c PredMap.
[209]53
[525]54    ///This function instantiates a \ref PredMap.
[244]55    ///\param g is the digraph, to which we would like to define the
[525]56    ///\ref PredMap.
[244]57    static PredMap *createPredMap(const Digraph &g)
[100]58    {
[244]59      return new PredMap(g);
[100]60    }
[244]61
[100]62    ///The type of the map that indicates which nodes are processed.
[209]63
[100]64    ///The type of the map that indicates which nodes are processed.
65    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
66    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
[525]67    ///Instantiates a \c ProcessedMap.
[209]68
[525]69    ///This function instantiates a \ref ProcessedMap.
[100]70    ///\param g is the digraph, to which
[525]71    ///we would like to define the \ref ProcessedMap
[100]72#ifdef DOXYGEN
[244]73    static ProcessedMap *createProcessedMap(const Digraph &g)
[100]74#else
[244]75    static ProcessedMap *createProcessedMap(const Digraph &)
[100]76#endif
77    {
78      return new ProcessedMap();
79    }
[244]80
[100]81    ///The type of the map that indicates which nodes are reached.
[209]82
[421]83    ///The type of the map that indicates which nodes are reached.
84    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
[100]85    typedef typename Digraph::template NodeMap<bool> ReachedMap;
[525]86    ///Instantiates a \c ReachedMap.
[209]87
[525]88    ///This function instantiates a \ref ReachedMap.
[244]89    ///\param g is the digraph, to which
[525]90    ///we would like to define the \ref ReachedMap.
[244]91    static ReachedMap *createReachedMap(const Digraph &g)
[100]92    {
[244]93      return new ReachedMap(g);
[100]94    }
[209]95
[244]96    ///The type of the map that stores the distances of the nodes.
97
98    ///The type of the map that stores the distances of the nodes.
[100]99    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
100    typedef typename Digraph::template NodeMap<int> DistMap;
[525]101    ///Instantiates a \c DistMap.
[209]102
[525]103    ///This function instantiates a \ref DistMap.
[244]104    ///\param g is the digraph, to which we would like to define the
[525]105    ///\ref DistMap.
[244]106    static DistMap *createDistMap(const Digraph &g)
[100]107    {
[244]108      return new DistMap(g);
[100]109    }
110  };
[209]111
[100]112  ///%BFS algorithm class.
[209]113
[100]114  ///\ingroup search
115  ///This class provides an efficient implementation of the %BFS algorithm.
116  ///
[278]117  ///There is also a \ref bfs() "function-type interface" for the BFS
[244]118  ///algorithm, which is convenient in the simplier cases and it can be
119  ///used easier.
120  ///
121  ///\tparam GR The type of the digraph the algorithm runs on.
[421]122  ///The default type is \ref ListDigraph.
[100]123#ifdef DOXYGEN
124  template <typename GR,
[209]125            typename TR>
[100]126#else
127  template <typename GR=ListDigraph,
[209]128            typename TR=BfsDefaultTraits<GR> >
[100]129#endif
130  class Bfs {
131  public:
132
[244]133    ///The type of the digraph the algorithm runs on.
[100]134    typedef typename TR::Digraph Digraph;
[209]135
[244]136    ///\brief The type of the map that stores the predecessor arcs of the
137    ///shortest paths.
[100]138    typedef typename TR::PredMap PredMap;
[244]139    ///The type of the map that stores the distances of the nodes.
140    typedef typename TR::DistMap DistMap;
141    ///The type of the map that indicates which nodes are reached.
[100]142    typedef typename TR::ReachedMap ReachedMap;
[244]143    ///The type of the map that indicates which nodes are processed.
[100]144    typedef typename TR::ProcessedMap ProcessedMap;
[244]145    ///The type of the paths.
146    typedef PredMapPath<Digraph, PredMap> Path;
147
[421]148    ///The \ref BfsDefaultTraits "traits class" of the algorithm.
[244]149    typedef TR Traits;
150
[100]151  private:
152
153    typedef typename Digraph::Node Node;
154    typedef typename Digraph::NodeIt NodeIt;
155    typedef typename Digraph::Arc Arc;
156    typedef typename Digraph::OutArcIt OutArcIt;
157
[244]158    //Pointer to the underlying digraph.
[100]159    const Digraph *G;
[244]160    //Pointer to the map of predecessor arcs.
[100]161    PredMap *_pred;
[244]162    //Indicates if _pred is locally allocated (true) or not.
[100]163    bool local_pred;
[244]164    //Pointer to the map of distances.
[100]165    DistMap *_dist;
[244]166    //Indicates if _dist is locally allocated (true) or not.
[100]167    bool local_dist;
[244]168    //Pointer to the map of reached status of the nodes.
[100]169    ReachedMap *_reached;
[244]170    //Indicates if _reached is locally allocated (true) or not.
[100]171    bool local_reached;
[244]172    //Pointer to the map of processed status of the nodes.
[100]173    ProcessedMap *_processed;
[244]174    //Indicates if _processed is locally allocated (true) or not.
[100]175    bool local_processed;
176
177    std::vector<typename Digraph::Node> _queue;
178    int _queue_head,_queue_tail,_queue_next_dist;
179    int _curr_dist;
180
[280]181    //Creates the maps if necessary.
[209]182    void create_maps()
[100]183    {
184      if(!_pred) {
[209]185        local_pred = true;
186        _pred = Traits::createPredMap(*G);
[100]187      }
188      if(!_dist) {
[209]189        local_dist = true;
190        _dist = Traits::createDistMap(*G);
[100]191      }
192      if(!_reached) {
[209]193        local_reached = true;
194        _reached = Traits::createReachedMap(*G);
[100]195      }
196      if(!_processed) {
[209]197        local_processed = true;
198        _processed = Traits::createProcessedMap(*G);
[100]199      }
200    }
201
202  protected:
[209]203
[100]204    Bfs() {}
[209]205
[100]206  public:
[209]207
[100]208    typedef Bfs Create;
209
[421]210    ///\name Named Template Parameters
[100]211
212    ///@{
213
214    template <class T>
[257]215    struct SetPredMapTraits : public Traits {
[100]216      typedef T PredMap;
[209]217      static PredMap *createPredMap(const Digraph &)
[100]218      {
[290]219        LEMON_ASSERT(false, "PredMap is not initialized");
220        return 0; // ignore warnings
[100]221      }
222    };
223    ///\brief \ref named-templ-param "Named parameter" for setting
[525]224    ///\c PredMap type.
[100]225    ///
[244]226    ///\ref named-templ-param "Named parameter" for setting
[525]227    ///\c PredMap type.
[421]228    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[100]229    template <class T>
[257]230    struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
231      typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
[100]232    };
[209]233
[100]234    template <class T>
[257]235    struct SetDistMapTraits : public Traits {
[100]236      typedef T DistMap;
[209]237      static DistMap *createDistMap(const Digraph &)
[100]238      {
[290]239        LEMON_ASSERT(false, "DistMap is not initialized");
240        return 0; // ignore warnings
[100]241      }
242    };
243    ///\brief \ref named-templ-param "Named parameter" for setting
[525]244    ///\c DistMap type.
[100]245    ///
[244]246    ///\ref named-templ-param "Named parameter" for setting
[525]247    ///\c DistMap type.
[421]248    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[100]249    template <class T>
[257]250    struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
251      typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
[100]252    };
[209]253
[100]254    template <class T>
[257]255    struct SetReachedMapTraits : public Traits {
[100]256      typedef T ReachedMap;
[209]257      static ReachedMap *createReachedMap(const Digraph &)
[100]258      {
[290]259        LEMON_ASSERT(false, "ReachedMap is not initialized");
260        return 0; // ignore warnings
[100]261      }
262    };
263    ///\brief \ref named-templ-param "Named parameter" for setting
[525]264    ///\c ReachedMap type.
[100]265    ///
[244]266    ///\ref named-templ-param "Named parameter" for setting
[525]267    ///\c ReachedMap type.
[421]268    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
[100]269    template <class T>
[257]270    struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
271      typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
[100]272    };
[209]273
[100]274    template <class T>
[257]275    struct SetProcessedMapTraits : public Traits {
[100]276      typedef T ProcessedMap;
[209]277      static ProcessedMap *createProcessedMap(const Digraph &)
[100]278      {
[290]279        LEMON_ASSERT(false, "ProcessedMap is not initialized");
280        return 0; // ignore warnings
[100]281      }
282    };
283    ///\brief \ref named-templ-param "Named parameter" for setting
[525]284    ///\c ProcessedMap type.
[100]285    ///
[244]286    ///\ref named-templ-param "Named parameter" for setting
[525]287    ///\c ProcessedMap type.
[421]288    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[100]289    template <class T>
[257]290    struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
291      typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
[100]292    };
[209]293
[257]294    struct SetStandardProcessedMapTraits : public Traits {
[100]295      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
[244]296      static ProcessedMap *createProcessedMap(const Digraph &g)
[100]297      {
[244]298        return new ProcessedMap(g);
[290]299        return 0; // ignore warnings
[100]300      }
301    };
[244]302    ///\brief \ref named-templ-param "Named parameter" for setting
[525]303    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
[100]304    ///
[244]305    ///\ref named-templ-param "Named parameter" for setting
[525]306    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
[100]307    ///If you don't set it explicitly, it will be automatically allocated.
[257]308    struct SetStandardProcessedMap :
309      public Bfs< Digraph, SetStandardProcessedMapTraits > {
310      typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
[100]311    };
[209]312
[100]313    ///@}
314
[209]315  public:
316
[100]317    ///Constructor.
[209]318
[244]319    ///Constructor.
320    ///\param g The digraph the algorithm runs on.
321    Bfs(const Digraph &g) :
322      G(&g),
[100]323      _pred(NULL), local_pred(false),
324      _dist(NULL), local_dist(false),
325      _reached(NULL), local_reached(false),
326      _processed(NULL), local_processed(false)
327    { }
[209]328
[100]329    ///Destructor.
[209]330    ~Bfs()
[100]331    {
332      if(local_pred) delete _pred;
333      if(local_dist) delete _dist;
334      if(local_reached) delete _reached;
335      if(local_processed) delete _processed;
336    }
337
[244]338    ///Sets the map that stores the predecessor arcs.
[100]339
[244]340    ///Sets the map that stores the predecessor arcs.
[421]341    ///If you don't use this function before calling \ref run(Node) "run()"
342    ///or \ref init(), an instance will be allocated automatically.
343    ///The destructor deallocates this automatically allocated map,
344    ///of course.
[100]345    ///\return <tt> (*this) </tt>
[209]346    Bfs &predMap(PredMap &m)
[100]347    {
348      if(local_pred) {
[209]349        delete _pred;
350        local_pred=false;
[100]351      }
352      _pred = &m;
353      return *this;
354    }
355
[244]356    ///Sets the map that indicates which nodes are reached.
[100]357
[244]358    ///Sets the map that indicates which nodes are reached.
[421]359    ///If you don't use this function before calling \ref run(Node) "run()"
360    ///or \ref init(), an instance will be allocated automatically.
361    ///The destructor deallocates this automatically allocated map,
362    ///of course.
[100]363    ///\return <tt> (*this) </tt>
[209]364    Bfs &reachedMap(ReachedMap &m)
[100]365    {
366      if(local_reached) {
[209]367        delete _reached;
368        local_reached=false;
[100]369      }
370      _reached = &m;
371      return *this;
372    }
373
[244]374    ///Sets the map that indicates which nodes are processed.
[100]375
[244]376    ///Sets the map that indicates which nodes are processed.
[421]377    ///If you don't use this function before calling \ref run(Node) "run()"
378    ///or \ref init(), an instance will be allocated automatically.
379    ///The destructor deallocates this automatically allocated map,
380    ///of course.
[100]381    ///\return <tt> (*this) </tt>
[209]382    Bfs &processedMap(ProcessedMap &m)
[100]383    {
384      if(local_processed) {
[209]385        delete _processed;
386        local_processed=false;
[100]387      }
388      _processed = &m;
389      return *this;
390    }
391
[244]392    ///Sets the map that stores the distances of the nodes.
[100]393
[244]394    ///Sets the map that stores the distances of the nodes calculated by
395    ///the algorithm.
[421]396    ///If you don't use this function before calling \ref run(Node) "run()"
397    ///or \ref init(), an instance will be allocated automatically.
398    ///The destructor deallocates this automatically allocated map,
399    ///of course.
[100]400    ///\return <tt> (*this) </tt>
[209]401    Bfs &distMap(DistMap &m)
[100]402    {
403      if(local_dist) {
[209]404        delete _dist;
405        local_dist=false;
[100]406      }
407      _dist = &m;
408      return *this;
409    }
410
411  public:
[244]412
[421]413    ///\name Execution Control
414    ///The simplest way to execute the BFS algorithm is to use one of the
415    ///member functions called \ref run(Node) "run()".\n
416    ///If you need more control on the execution, first you have to call
417    ///\ref init(), then you can add several source nodes with
418    ///\ref addSource(). Finally the actual path computation can be
419    ///performed with one of the \ref start() functions.
[100]420
421    ///@{
422
[421]423    ///\brief Initializes the internal data structures.
424    ///
[244]425    ///Initializes the internal data structures.
[100]426    void init()
427    {
428      create_maps();
429      _queue.resize(countNodes(*G));
430      _queue_head=_queue_tail=0;
431      _curr_dist=1;
432      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
[209]433        _pred->set(u,INVALID);
434        _reached->set(u,false);
435        _processed->set(u,false);
[100]436      }
437    }
[209]438
[100]439    ///Adds a new source node.
440
441    ///Adds a new source node to the set of nodes to be processed.
442    ///
443    void addSource(Node s)
444    {
445      if(!(*_reached)[s])
[209]446        {
447          _reached->set(s,true);
448          _pred->set(s,INVALID);
449          _dist->set(s,0);
450          _queue[_queue_head++]=s;
451          _queue_next_dist=_queue_head;
452        }
[100]453    }
[209]454
[100]455    ///Processes the next node.
456
457    ///Processes the next node.
458    ///
459    ///\return The processed node.
460    ///
[244]461    ///\pre The queue must not be empty.
[100]462    Node processNextNode()
463    {
464      if(_queue_tail==_queue_next_dist) {
[209]465        _curr_dist++;
466        _queue_next_dist=_queue_head;
[100]467      }
468      Node n=_queue[_queue_tail++];
469      _processed->set(n,true);
470      Node m;
471      for(OutArcIt e(*G,n);e!=INVALID;++e)
[209]472        if(!(*_reached)[m=G->target(e)]) {
473          _queue[_queue_head++]=m;
474          _reached->set(m,true);
475          _pred->set(m,e);
476          _dist->set(m,_curr_dist);
477        }
[100]478      return n;
479    }
480
481    ///Processes the next node.
482
[244]483    ///Processes the next node and checks if the given target node
[100]484    ///is reached. If the target node is reachable from the processed
[244]485    ///node, then the \c reach parameter will be set to \c true.
[100]486    ///
487    ///\param target The target node.
[244]488    ///\retval reach Indicates if the target node is reached.
489    ///It should be initially \c false.
490    ///
[100]491    ///\return The processed node.
492    ///
[244]493    ///\pre The queue must not be empty.
[100]494    Node processNextNode(Node target, bool& reach)
495    {
496      if(_queue_tail==_queue_next_dist) {
[209]497        _curr_dist++;
498        _queue_next_dist=_queue_head;
[100]499      }
500      Node n=_queue[_queue_tail++];
501      _processed->set(n,true);
502      Node m;
503      for(OutArcIt e(*G,n);e!=INVALID;++e)
[209]504        if(!(*_reached)[m=G->target(e)]) {
505          _queue[_queue_head++]=m;
506          _reached->set(m,true);
507          _pred->set(m,e);
508          _dist->set(m,_curr_dist);
[100]509          reach = reach || (target == m);
[209]510        }
[100]511      return n;
512    }
513
514    ///Processes the next node.
515
[244]516    ///Processes the next node and checks if at least one of reached
517    ///nodes has \c true value in the \c nm node map. If one node
518    ///with \c true value is reachable from the processed node, then the
519    ///\c rnode parameter will be set to the first of such nodes.
[100]520    ///
[244]521    ///\param nm A \c bool (or convertible) node map that indicates the
522    ///possible targets.
[100]523    ///\retval rnode The reached target node.
[244]524    ///It should be initially \c INVALID.
525    ///
[100]526    ///\return The processed node.
527    ///
[244]528    ///\pre The queue must not be empty.
[100]529    template<class NM>
530    Node processNextNode(const NM& nm, Node& rnode)
531    {
532      if(_queue_tail==_queue_next_dist) {
[209]533        _curr_dist++;
534        _queue_next_dist=_queue_head;
[100]535      }
536      Node n=_queue[_queue_tail++];
537      _processed->set(n,true);
538      Node m;
539      for(OutArcIt e(*G,n);e!=INVALID;++e)
[209]540        if(!(*_reached)[m=G->target(e)]) {
541          _queue[_queue_head++]=m;
542          _reached->set(m,true);
543          _pred->set(m,e);
544          _dist->set(m,_curr_dist);
545          if (nm[m] && rnode == INVALID) rnode = m;
546        }
[100]547      return n;
548    }
[209]549
[244]550    ///The next node to be processed.
[100]551
[244]552    ///Returns the next node to be processed or \c INVALID if the queue
553    ///is empty.
554    Node nextNode() const
[209]555    {
[100]556      return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
557    }
[209]558
[421]559    ///Returns \c false if there are nodes to be processed.
560
561    ///Returns \c false if there are nodes to be processed
562    ///in the queue.
[244]563    bool emptyQueue() const { return _queue_tail==_queue_head; }
564
[100]565    ///Returns the number of the nodes to be processed.
[209]566
[421]567    ///Returns the number of the nodes to be processed
568    ///in the queue.
[244]569    int queueSize() const { return _queue_head-_queue_tail; }
[209]570
[100]571    ///Executes the algorithm.
572
573    ///Executes the algorithm.
574    ///
[244]575    ///This method runs the %BFS algorithm from the root node(s)
576    ///in order to compute the shortest path to each node.
[100]577    ///
[244]578    ///The algorithm computes
579    ///- the shortest path tree (forest),
580    ///- the distance of each node from the root(s).
581    ///
582    ///\pre init() must be called and at least one root node should be
583    ///added with addSource() before using this function.
584    ///
585    ///\note <tt>b.start()</tt> is just a shortcut of the following code.
586    ///\code
587    ///  while ( !b.emptyQueue() ) {
588    ///    b.processNextNode();
589    ///  }
590    ///\endcode
[100]591    void start()
592    {
593      while ( !emptyQueue() ) processNextNode();
594    }
[209]595
[244]596    ///Executes the algorithm until the given target node is reached.
[100]597
[244]598    ///Executes the algorithm until the given target node is reached.
[100]599    ///
600    ///This method runs the %BFS algorithm from the root node(s)
[286]601    ///in order to compute the shortest path to \c t.
[244]602    ///
[100]603    ///The algorithm computes
[286]604    ///- the shortest path to \c t,
605    ///- the distance of \c t from the root(s).
[244]606    ///
607    ///\pre init() must be called and at least one root node should be
608    ///added with addSource() before using this function.
609    ///
610    ///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
611    ///\code
612    ///  bool reach = false;
613    ///  while ( !b.emptyQueue() && !reach ) {
614    ///    b.processNextNode(t, reach);
615    ///  }
616    ///\endcode
[286]617    void start(Node t)
[100]618    {
619      bool reach = false;
[286]620      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
[100]621    }
[209]622
[100]623    ///Executes the algorithm until a condition is met.
624
625    ///Executes the algorithm until a condition is met.
626    ///
[244]627    ///This method runs the %BFS algorithm from the root node(s) in
628    ///order to compute the shortest path to a node \c v with
629    /// <tt>nm[v]</tt> true, if such a node can be found.
[100]630    ///
[244]631    ///\param nm A \c bool (or convertible) node map. The algorithm
632    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
[100]633    ///
634    ///\return The reached node \c v with <tt>nm[v]</tt> true or
635    ///\c INVALID if no such node was found.
[244]636    ///
637    ///\pre init() must be called and at least one root node should be
638    ///added with addSource() before using this function.
639    ///
640    ///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
641    ///\code
642    ///  Node rnode = INVALID;
643    ///  while ( !b.emptyQueue() && rnode == INVALID ) {
644    ///    b.processNextNode(nm, rnode);
645    ///  }
646    ///  return rnode;
647    ///\endcode
648    template<class NodeBoolMap>
649    Node start(const NodeBoolMap &nm)
[100]650    {
651      Node rnode = INVALID;
652      while ( !emptyQueue() && rnode == INVALID ) {
[209]653        processNextNode(nm, rnode);
[100]654      }
655      return rnode;
656    }
[209]657
[286]658    ///Runs the algorithm from the given source node.
[209]659
[244]660    ///This method runs the %BFS algorithm from node \c s
661    ///in order to compute the shortest path to each node.
[100]662    ///
[244]663    ///The algorithm computes
664    ///- the shortest path tree,
665    ///- the distance of each node from the root.
666    ///
667    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
[100]668    ///\code
669    ///  b.init();
670    ///  b.addSource(s);
671    ///  b.start();
672    ///\endcode
673    void run(Node s) {
674      init();
675      addSource(s);
676      start();
677    }
[209]678
[100]679    ///Finds the shortest path between \c s and \c t.
[209]680
[244]681    ///This method runs the %BFS algorithm from node \c s
[286]682    ///in order to compute the shortest path to node \c t
683    ///(it stops searching when \c t is processed).
[100]684    ///
[286]685    ///\return \c true if \c t is reachable form \c s.
[244]686    ///
687    ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
688    ///shortcut of the following code.
[100]689    ///\code
690    ///  b.init();
691    ///  b.addSource(s);
692    ///  b.start(t);
693    ///\endcode
[286]694    bool run(Node s,Node t) {
[100]695      init();
696      addSource(s);
697      start(t);
[286]698      return reached(t);
[100]699    }
[209]700
[244]701    ///Runs the algorithm to visit all nodes in the digraph.
702
703    ///This method runs the %BFS algorithm in order to
704    ///compute the shortest path to each node.
705    ///
706    ///The algorithm computes
707    ///- the shortest path tree (forest),
708    ///- the distance of each node from the root(s).
709    ///
710    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
711    ///\code
712    ///  b.init();
713    ///  for (NodeIt n(gr); n != INVALID; ++n) {
714    ///    if (!b.reached(n)) {
715    ///      b.addSource(n);
716    ///      b.start();
717    ///    }
718    ///  }
719    ///\endcode
720    void run() {
721      init();
722      for (NodeIt n(*G); n != INVALID; ++n) {
723        if (!reached(n)) {
724          addSource(n);
725          start();
726        }
727      }
728    }
729
[100]730    ///@}
731
732    ///\name Query Functions
[421]733    ///The results of the BFS algorithm can be obtained using these
[100]734    ///functions.\n
[421]735    ///Either \ref run(Node) "run()" or \ref start() should be called
736    ///before using them.
[209]737
[100]738    ///@{
739
[244]740    ///The shortest path to a node.
[100]741
[244]742    ///Returns the shortest path to a node.
743    ///
[421]744    ///\warning \c t should be reached from the root(s).
[244]745    ///
[421]746    ///\pre Either \ref run(Node) "run()" or \ref init()
747    ///must be called before using this function.
[244]748    Path path(Node t) const { return Path(*G, *_pred, t); }
[100]749
750    ///The distance of a node from the root(s).
751
752    ///Returns the distance of a node from the root(s).
[244]753    ///
[421]754    ///\warning If node \c v is not reached from the root(s), then
[244]755    ///the return value of this function is undefined.
756    ///
[421]757    ///\pre Either \ref run(Node) "run()" or \ref init()
758    ///must be called before using this function.
[100]759    int dist(Node v) const { return (*_dist)[v]; }
760
[244]761    ///Returns the 'previous arc' of the shortest path tree for a node.
[100]762
[244]763    ///This function returns the 'previous arc' of the shortest path
764    ///tree for the node \c v, i.e. it returns the last arc of a
[421]765    ///shortest path from a root to \c v. It is \c INVALID if \c v
766    ///is not reached from the root(s) or if \c v is a root.
[244]767    ///
768    ///The shortest path tree used here is equal to the shortest path
769    ///tree used in \ref predNode().
770    ///
[421]771    ///\pre Either \ref run(Node) "run()" or \ref init()
772    ///must be called before using this function.
[100]773    Arc predArc(Node v) const { return (*_pred)[v];}
774
[244]775    ///Returns the 'previous node' of the shortest path tree for a node.
[100]776
[244]777    ///This function returns the 'previous node' of the shortest path
778    ///tree for the node \c v, i.e. it returns the last but one node
[421]779    ///from a shortest path from a root to \c v. It is \c INVALID
780    ///if \c v is not reached from the root(s) or if \c v is a root.
[244]781    ///
[100]782    ///The shortest path tree used here is equal to the shortest path
783    ///tree used in \ref predArc().
[244]784    ///
[421]785    ///\pre Either \ref run(Node) "run()" or \ref init()
786    ///must be called before using this function.
[100]787    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
[209]788                                  G->source((*_pred)[v]); }
789
[244]790    ///\brief Returns a const reference to the node map that stores the
791    /// distances of the nodes.
792    ///
793    ///Returns a const reference to the node map that stores the distances
794    ///of the nodes calculated by the algorithm.
795    ///
[421]796    ///\pre Either \ref run(Node) "run()" or \ref init()
[244]797    ///must be called before using this function.
[100]798    const DistMap &distMap() const { return *_dist;}
[209]799
[244]800    ///\brief Returns a const reference to the node map that stores the
801    ///predecessor arcs.
802    ///
803    ///Returns a const reference to the node map that stores the predecessor
804    ///arcs, which form the shortest path tree.
805    ///
[421]806    ///\pre Either \ref run(Node) "run()" or \ref init()
[100]807    ///must be called before using this function.
808    const PredMap &predMap() const { return *_pred;}
[209]809
[421]810    ///Checks if a node is reached from the root(s).
[100]811
[421]812    ///Returns \c true if \c v is reached from the root(s).
813    ///
814    ///\pre Either \ref run(Node) "run()" or \ref init()
[100]815    ///must be called before using this function.
[244]816    bool reached(Node v) const { return (*_reached)[v]; }
[209]817
[100]818    ///@}
819  };
820
[244]821  ///Default traits class of bfs() function.
[100]822
[244]823  ///Default traits class of bfs() function.
[157]824  ///\tparam GR Digraph type.
[100]825  template<class GR>
826  struct BfsWizardDefaultTraits
827  {
[244]828    ///The type of the digraph the algorithm runs on.
[100]829    typedef GR Digraph;
[244]830
831    ///\brief The type of the map that stores the predecessor
[100]832    ///arcs of the shortest paths.
[209]833    ///
[244]834    ///The type of the map that stores the predecessor
[100]835    ///arcs of the shortest paths.
836    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[278]837    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
[301]838    ///Instantiates a PredMap.
[209]839
[301]840    ///This function instantiates a PredMap.
[244]841    ///\param g is the digraph, to which we would like to define the
[301]842    ///PredMap.
[244]843    static PredMap *createPredMap(const Digraph &g)
[100]844    {
[278]845      return new PredMap(g);
[100]846    }
847
848    ///The type of the map that indicates which nodes are processed.
[209]849
[100]850    ///The type of the map that indicates which nodes are processed.
851    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[278]852    ///By default it is a NullMap.
[100]853    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
[301]854    ///Instantiates a ProcessedMap.
[209]855
[301]856    ///This function instantiates a ProcessedMap.
[100]857    ///\param g is the digraph, to which
[301]858    ///we would like to define the ProcessedMap.
[100]859#ifdef DOXYGEN
[244]860    static ProcessedMap *createProcessedMap(const Digraph &g)
[100]861#else
[244]862    static ProcessedMap *createProcessedMap(const Digraph &)
[100]863#endif
864    {
865      return new ProcessedMap();
866    }
[244]867
[100]868    ///The type of the map that indicates which nodes are reached.
[209]869
[100]870    ///The type of the map that indicates which nodes are reached.
[244]871    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
[100]872    typedef typename Digraph::template NodeMap<bool> ReachedMap;
[301]873    ///Instantiates a ReachedMap.
[209]874
[301]875    ///This function instantiates a ReachedMap.
[244]876    ///\param g is the digraph, to which
[301]877    ///we would like to define the ReachedMap.
[244]878    static ReachedMap *createReachedMap(const Digraph &g)
[100]879    {
[244]880      return new ReachedMap(g);
[100]881    }
[209]882
[244]883    ///The type of the map that stores the distances of the nodes.
884
885    ///The type of the map that stores the distances of the nodes.
[100]886    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[278]887    typedef typename Digraph::template NodeMap<int> DistMap;
[301]888    ///Instantiates a DistMap.
[209]889
[301]890    ///This function instantiates a DistMap.
[210]891    ///\param g is the digraph, to which we would like to define
[301]892    ///the DistMap
[244]893    static DistMap *createDistMap(const Digraph &g)
[100]894    {
[278]895      return new DistMap(g);
[100]896    }
[278]897
898    ///The type of the shortest paths.
899
900    ///The type of the shortest paths.
901    ///It must meet the \ref concepts::Path "Path" concept.
902    typedef lemon::Path<Digraph> Path;
[100]903  };
[209]904
[301]905  /// Default traits class used by BfsWizard
[100]906
907  /// To make it easier to use Bfs algorithm
[244]908  /// we have created a wizard class.
[100]909  /// This \ref BfsWizard class needs default traits,
[244]910  /// as well as the \ref Bfs class.
[100]911  /// The \ref BfsWizardBase is a class to be the default traits of the
912  /// \ref BfsWizard class.
913  template<class GR>
914  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
915  {
916
917    typedef BfsWizardDefaultTraits<GR> Base;
918  protected:
[244]919    //The type of the nodes in the digraph.
[100]920    typedef typename Base::Digraph::Node Node;
921
[244]922    //Pointer to the digraph the algorithm runs on.
[100]923    void *_g;
[244]924    //Pointer to the map of reached nodes.
[100]925    void *_reached;
[244]926    //Pointer to the map of processed nodes.
[100]927    void *_processed;
[244]928    //Pointer to the map of predecessors arcs.
[100]929    void *_pred;
[244]930    //Pointer to the map of distances.
[100]931    void *_dist;
[278]932    //Pointer to the shortest path to the target node.
933    void *_path;
934    //Pointer to the distance of the target node.
935    int *_di;
[209]936
[100]937    public:
938    /// Constructor.
[209]939
[100]940    /// This constructor does not require parameters, therefore it initiates
[278]941    /// all of the attributes to \c 0.
[100]942    BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
[278]943                      _dist(0), _path(0), _di(0) {}
[100]944
945    /// Constructor.
[209]946
[278]947    /// This constructor requires one parameter,
948    /// others are initiated to \c 0.
[244]949    /// \param g The digraph the algorithm runs on.
[278]950    BfsWizardBase(const GR &g) :
[209]951      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
[278]952      _reached(0), _processed(0), _pred(0), _dist(0),  _path(0), _di(0) {}
[100]953
954  };
[209]955
[278]956  /// Auxiliary class for the function-type interface of BFS algorithm.
[100]957
[278]958  /// This auxiliary class is created to implement the
959  /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
[421]960  /// It does not have own \ref run(Node) "run()" method, it uses the
961  /// functions and features of the plain \ref Bfs.
[100]962  ///
[278]963  /// This class should only be used through the \ref bfs() function,
964  /// which makes it easier to use the algorithm.
[100]965  template<class TR>
966  class BfsWizard : public TR
967  {
968    typedef TR Base;
969
[244]970    ///The type of the digraph the algorithm runs on.
[100]971    typedef typename TR::Digraph Digraph;
[244]972
[100]973    typedef typename Digraph::Node Node;
974    typedef typename Digraph::NodeIt NodeIt;
975    typedef typename Digraph::Arc Arc;
976    typedef typename Digraph::OutArcIt OutArcIt;
[209]977
[244]978    ///\brief The type of the map that stores the predecessor
[100]979    ///arcs of the shortest paths.
980    typedef typename TR::PredMap PredMap;
[244]981    ///\brief The type of the map that stores the distances of the nodes.
[100]982    typedef typename TR::DistMap DistMap;
[244]983    ///\brief The type of the map that indicates which nodes are reached.
984    typedef typename TR::ReachedMap ReachedMap;
985    ///\brief The type of the map that indicates which nodes are processed.
986    typedef typename TR::ProcessedMap ProcessedMap;
[278]987    ///The type of the shortest paths
988    typedef typename TR::Path Path;
[100]989
990  public:
[244]991
[100]992    /// Constructor.
993    BfsWizard() : TR() {}
994
995    /// Constructor that requires parameters.
996
997    /// Constructor that requires parameters.
998    /// These parameters will be the default values for the traits class.
[278]999    /// \param g The digraph the algorithm runs on.
1000    BfsWizard(const Digraph &g) :
1001      TR(g) {}
[100]1002
1003    ///Copy constructor
1004    BfsWizard(const TR &b) : TR(b) {}
1005
1006    ~BfsWizard() {}
1007
[278]1008    ///Runs BFS algorithm from the given source node.
[209]1009
[278]1010    ///This method runs BFS algorithm from node \c s
1011    ///in order to compute the shortest path to each node.
1012    void run(Node s)
1013    {
1014      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1015      if (Base::_pred)
1016        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1017      if (Base::_dist)
1018        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1019      if (Base::_reached)
1020        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1021      if (Base::_processed)
1022        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1023      if (s!=INVALID)
1024        alg.run(s);
1025      else
1026        alg.run();
1027    }
1028
1029    ///Finds the shortest path between \c s and \c t.
1030
1031    ///This method runs BFS algorithm from node \c s
1032    ///in order to compute the shortest path to node \c t
1033    ///(it stops searching when \c t is processed).
1034    ///
1035    ///\return \c true if \c t is reachable form \c s.
1036    bool run(Node s, Node t)
1037    {
1038      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1039      if (Base::_pred)
1040        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1041      if (Base::_dist)
1042        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1043      if (Base::_reached)
1044        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1045      if (Base::_processed)
1046        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1047      alg.run(s,t);
1048      if (Base::_path)
1049        *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1050      if (Base::_di)
1051        *Base::_di = alg.dist(t);
1052      return alg.reached(t);
1053    }
1054
1055    ///Runs BFS algorithm to visit all nodes in the digraph.
1056
1057    ///This method runs BFS algorithm in order to compute
1058    ///the shortest path to each node.
[100]1059    void run()
1060    {
[278]1061      run(INVALID);
[100]1062    }
[209]1063
[244]1064    template<class T>
[257]1065    struct SetPredMapBase : public Base {
[244]1066      typedef T PredMap;
1067      static PredMap *createPredMap(const Digraph &) { return 0; };
[257]1068      SetPredMapBase(const TR &b) : TR(b) {}
[244]1069    };
[278]1070    ///\brief \ref named-func-param "Named parameter"
[301]1071    ///for setting PredMap object.
[244]1072    ///
[278]1073    ///\ref named-func-param "Named parameter"
[301]1074    ///for setting PredMap object.
[244]1075    template<class T>
[257]1076    BfsWizard<SetPredMapBase<T> > predMap(const T &t)
[244]1077    {
1078      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
[257]1079      return BfsWizard<SetPredMapBase<T> >(*this);
[244]1080    }
1081
1082    template<class T>
[257]1083    struct SetReachedMapBase : public Base {
[244]1084      typedef T ReachedMap;
1085      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
[257]1086      SetReachedMapBase(const TR &b) : TR(b) {}
[244]1087    };
[278]1088    ///\brief \ref named-func-param "Named parameter"
[301]1089    ///for setting ReachedMap object.
[244]1090    ///
[278]1091    /// \ref named-func-param "Named parameter"
[301]1092    ///for setting ReachedMap object.
[244]1093    template<class T>
[257]1094    BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
[244]1095    {
1096      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
[257]1097      return BfsWizard<SetReachedMapBase<T> >(*this);
[244]1098    }
1099
1100    template<class T>
[278]1101    struct SetDistMapBase : public Base {
1102      typedef T DistMap;
1103      static DistMap *createDistMap(const Digraph &) { return 0; };
1104      SetDistMapBase(const TR &b) : TR(b) {}
1105    };
1106    ///\brief \ref named-func-param "Named parameter"
[301]1107    ///for setting DistMap object.
[278]1108    ///
1109    /// \ref named-func-param "Named parameter"
[301]1110    ///for setting DistMap object.
[278]1111    template<class T>
1112    BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1113    {
1114      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1115      return BfsWizard<SetDistMapBase<T> >(*this);
1116    }
1117
1118    template<class T>
[257]1119    struct SetProcessedMapBase : public Base {
[244]1120      typedef T ProcessedMap;
1121      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
[257]1122      SetProcessedMapBase(const TR &b) : TR(b) {}
[244]1123    };
[278]1124    ///\brief \ref named-func-param "Named parameter"
[301]1125    ///for setting ProcessedMap object.
[244]1126    ///
[278]1127    /// \ref named-func-param "Named parameter"
[301]1128    ///for setting ProcessedMap object.
[244]1129    template<class T>
[257]1130    BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
[244]1131    {
1132      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
[257]1133      return BfsWizard<SetProcessedMapBase<T> >(*this);
[244]1134    }
1135
1136    template<class T>
[278]1137    struct SetPathBase : public Base {
1138      typedef T Path;
1139      SetPathBase(const TR &b) : TR(b) {}
[244]1140    };
[278]1141    ///\brief \ref named-func-param "Named parameter"
1142    ///for getting the shortest path to the target node.
[244]1143    ///
[278]1144    ///\ref named-func-param "Named parameter"
1145    ///for getting the shortest path to the target node.
[244]1146    template<class T>
[278]1147    BfsWizard<SetPathBase<T> > path(const T &t)
[244]1148    {
[278]1149      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1150      return BfsWizard<SetPathBase<T> >(*this);
1151    }
1152
1153    ///\brief \ref named-func-param "Named parameter"
1154    ///for getting the distance of the target node.
1155    ///
1156    ///\ref named-func-param "Named parameter"
1157    ///for getting the distance of the target node.
1158    BfsWizard dist(const int &d)
1159    {
1160      Base::_di=const_cast<int*>(&d);
1161      return *this;
[244]1162    }
1163
[100]1164  };
[209]1165
[278]1166  ///Function-type interface for BFS algorithm.
[100]1167
1168  /// \ingroup search
[278]1169  ///Function-type interface for BFS algorithm.
[100]1170  ///
[278]1171  ///This function also has several \ref named-func-param "named parameters",
[100]1172  ///they are declared as the members of class \ref BfsWizard.
[278]1173  ///The following examples show how to use these parameters.
[100]1174  ///\code
[278]1175  ///  // Compute shortest path from node s to each node
1176  ///  bfs(g).predMap(preds).distMap(dists).run(s);
1177  ///
1178  ///  // Compute shortest path from s to t
1179  ///  bool reached = bfs(g).path(p).dist(d).run(s,t);
[100]1180  ///\endcode
[421]1181  ///\warning Don't forget to put the \ref BfsWizard::run(Node) "run()"
[100]1182  ///to the end of the parameter list.
1183  ///\sa BfsWizard
1184  ///\sa Bfs
1185  template<class GR>
1186  BfsWizard<BfsWizardBase<GR> >
[278]1187  bfs(const GR &digraph)
[100]1188  {
[278]1189    return BfsWizard<BfsWizardBase<GR> >(digraph);
[100]1190  }
1191
1192#ifdef DOXYGEN
[244]1193  /// \brief Visitor class for BFS.
[209]1194  ///
[100]1195  /// This class defines the interface of the BfsVisit events, and
[244]1196  /// it could be the base of a real visitor class.
[525]1197  template <typename GR>
[100]1198  struct BfsVisitor {
[525]1199    typedef GR Digraph;
[100]1200    typedef typename Digraph::Arc Arc;
1201    typedef typename Digraph::Node Node;
[244]1202    /// \brief Called for the source node(s) of the BFS.
[209]1203    ///
[244]1204    /// This function is called for the source node(s) of the BFS.
1205    void start(const Node& node) {}
1206    /// \brief Called when a node is reached first time.
1207    ///
1208    /// This function is called when a node is reached first time.
1209    void reach(const Node& node) {}
1210    /// \brief Called when a node is processed.
1211    ///
1212    /// This function is called when a node is processed.
1213    void process(const Node& node) {}
1214    /// \brief Called when an arc reaches a new node.
1215    ///
1216    /// This function is called when the BFS finds an arc whose target node
1217    /// is not reached yet.
[100]1218    void discover(const Arc& arc) {}
[244]1219    /// \brief Called when an arc is examined but its target node is
[100]1220    /// already discovered.
[209]1221    ///
[244]1222    /// This function is called when an arc is examined but its target node is
[100]1223    /// already discovered.
1224    void examine(const Arc& arc) {}
1225  };
1226#else
[525]1227  template <typename GR>
[100]1228  struct BfsVisitor {
[525]1229    typedef GR Digraph;
[100]1230    typedef typename Digraph::Arc Arc;
1231    typedef typename Digraph::Node Node;
[244]1232    void start(const Node&) {}
1233    void reach(const Node&) {}
1234    void process(const Node&) {}
[100]1235    void discover(const Arc&) {}
1236    void examine(const Arc&) {}
1237
1238    template <typename _Visitor>
1239    struct Constraints {
1240      void constraints() {
[209]1241        Arc arc;
1242        Node node;
[244]1243        visitor.start(node);
1244        visitor.reach(node);
1245        visitor.process(node);
[209]1246        visitor.discover(arc);
1247        visitor.examine(arc);
[100]1248      }
1249      _Visitor& visitor;
[1125]1250      Constraints() {}
[100]1251    };
1252  };
1253#endif
1254
1255  /// \brief Default traits class of BfsVisit class.
1256  ///
1257  /// Default traits class of BfsVisit class.
[525]1258  /// \tparam GR The type of the digraph the algorithm runs on.
1259  template<class GR>
[100]1260  struct BfsVisitDefaultTraits {
1261
[244]1262    /// \brief The type of the digraph the algorithm runs on.
[525]1263    typedef GR Digraph;
[100]1264
1265    /// \brief The type of the map that indicates which nodes are reached.
[209]1266    ///
[100]1267    /// The type of the map that indicates which nodes are reached.
[244]1268    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
[100]1269    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1270
[301]1271    /// \brief Instantiates a ReachedMap.
[100]1272    ///
[301]1273    /// This function instantiates a ReachedMap.
[100]1274    /// \param digraph is the digraph, to which
[301]1275    /// we would like to define the ReachedMap.
[100]1276    static ReachedMap *createReachedMap(const Digraph &digraph) {
1277      return new ReachedMap(digraph);
1278    }
1279
1280  };
1281
1282  /// \ingroup search
[209]1283  ///
[525]1284  /// \brief BFS algorithm class with visitor interface.
[209]1285  ///
[525]1286  /// This class provides an efficient implementation of the BFS algorithm
[100]1287  /// with visitor interface.
1288  ///
[525]1289  /// The BfsVisit class provides an alternative interface to the Bfs
[100]1290  /// class. It works with callback mechanism, the BfsVisit object calls
[244]1291  /// the member functions of the \c Visitor class on every BFS event.
[100]1292  ///
[252]1293  /// This interface of the BFS algorithm should be used in special cases
1294  /// when extra actions have to be performed in connection with certain
1295  /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1296  /// instead.
1297  ///
[525]1298  /// \tparam GR The type of the digraph the algorithm runs on.
1299  /// The default type is \ref ListDigraph.
1300  /// The value of GR is not used directly by \ref BfsVisit,
1301  /// it is only passed to \ref BfsVisitDefaultTraits.
1302  /// \tparam VS The Visitor type that is used by the algorithm.
1303  /// \ref BfsVisitor "BfsVisitor<GR>" is an empty visitor, which
[244]1304  /// does not observe the BFS events. If you want to observe the BFS
1305  /// events, you should implement your own visitor class.
[525]1306  /// \tparam TR Traits class to set various data types used by the
[100]1307  /// algorithm. The default traits class is
[525]1308  /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<GR>".
[100]1309  /// See \ref BfsVisitDefaultTraits for the documentation of
[244]1310  /// a BFS visit traits class.
[100]1311#ifdef DOXYGEN
[525]1312  template <typename GR, typename VS, typename TR>
[100]1313#else
[525]1314  template <typename GR = ListDigraph,
1315            typename VS = BfsVisitor<GR>,
1316            typename TR = BfsVisitDefaultTraits<GR> >
[100]1317#endif
1318  class BfsVisit {
1319  public:
[209]1320
[244]1321    ///The traits class.
[525]1322    typedef TR Traits;
[100]1323
[244]1324    ///The type of the digraph the algorithm runs on.
[100]1325    typedef typename Traits::Digraph Digraph;
1326
[244]1327    ///The visitor type used by the algorithm.
[525]1328    typedef VS Visitor;
[100]1329
[244]1330    ///The type of the map that indicates which nodes are reached.
[100]1331    typedef typename Traits::ReachedMap ReachedMap;
1332
1333  private:
1334
1335    typedef typename Digraph::Node Node;
1336    typedef typename Digraph::NodeIt NodeIt;
1337    typedef typename Digraph::Arc Arc;
1338    typedef typename Digraph::OutArcIt OutArcIt;
1339
[244]1340    //Pointer to the underlying digraph.
[100]1341    const Digraph *_digraph;
[244]1342    //Pointer to the visitor object.
[100]1343    Visitor *_visitor;
[244]1344    //Pointer to the map of reached status of the nodes.
[100]1345    ReachedMap *_reached;
[244]1346    //Indicates if _reached is locally allocated (true) or not.
[100]1347    bool local_reached;
1348
1349    std::vector<typename Digraph::Node> _list;
1350    int _list_front, _list_back;
1351
[280]1352    //Creates the maps if necessary.
[100]1353    void create_maps() {
1354      if(!_reached) {
[209]1355        local_reached = true;
1356        _reached = Traits::createReachedMap(*_digraph);
[100]1357      }
1358    }
1359
1360  protected:
1361
1362    BfsVisit() {}
[209]1363
[100]1364  public:
1365
1366    typedef BfsVisit Create;
1367
[421]1368    /// \name Named Template Parameters
[100]1369
1370    ///@{
1371    template <class T>
[257]1372    struct SetReachedMapTraits : public Traits {
[100]1373      typedef T ReachedMap;
1374      static ReachedMap *createReachedMap(const Digraph &digraph) {
[290]1375        LEMON_ASSERT(false, "ReachedMap is not initialized");
1376        return 0; // ignore warnings
[100]1377      }
1378    };
[209]1379    /// \brief \ref named-templ-param "Named parameter" for setting
[244]1380    /// ReachedMap type.
[100]1381    ///
[244]1382    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
[100]1383    template <class T>
[257]1384    struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1385                                            SetReachedMapTraits<T> > {
1386      typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
[100]1387    };
1388    ///@}
1389
[209]1390  public:
1391
[100]1392    /// \brief Constructor.
1393    ///
1394    /// Constructor.
1395    ///
[244]1396    /// \param digraph The digraph the algorithm runs on.
1397    /// \param visitor The visitor object of the algorithm.
[209]1398    BfsVisit(const Digraph& digraph, Visitor& visitor)
[100]1399      : _digraph(&digraph), _visitor(&visitor),
[209]1400        _reached(0), local_reached(false) {}
1401
[100]1402    /// \brief Destructor.
1403    ~BfsVisit() {
1404      if(local_reached) delete _reached;
1405    }
1406
[244]1407    /// \brief Sets the map that indicates which nodes are reached.
[100]1408    ///
[244]1409    /// Sets the map that indicates which nodes are reached.
[421]1410    /// If you don't use this function before calling \ref run(Node) "run()"
1411    /// or \ref init(), an instance will be allocated automatically.
1412    /// The destructor deallocates this automatically allocated map,
1413    /// of course.
[100]1414    /// \return <tt> (*this) </tt>
1415    BfsVisit &reachedMap(ReachedMap &m) {
1416      if(local_reached) {
[209]1417        delete _reached;
1418        local_reached = false;
[100]1419      }
1420      _reached = &m;
1421      return *this;
1422    }
1423
1424  public:
[244]1425
[421]1426    /// \name Execution Control
1427    /// The simplest way to execute the BFS algorithm is to use one of the
1428    /// member functions called \ref run(Node) "run()".\n
1429    /// If you need more control on the execution, first you have to call
1430    /// \ref init(), then you can add several source nodes with
1431    /// \ref addSource(). Finally the actual path computation can be
1432    /// performed with one of the \ref start() functions.
[100]1433
1434    /// @{
[244]1435
[100]1436    /// \brief Initializes the internal data structures.
1437    ///
1438    /// Initializes the internal data structures.
1439    void init() {
1440      create_maps();
1441      _list.resize(countNodes(*_digraph));
1442      _list_front = _list_back = -1;
1443      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
[209]1444        _reached->set(u, false);
[100]1445      }
1446    }
[209]1447
[100]1448    /// \brief Adds a new source node.
1449    ///
1450    /// Adds a new source node to the set of nodes to be processed.
1451    void addSource(Node s) {
1452      if(!(*_reached)[s]) {
[209]1453          _reached->set(s,true);
1454          _visitor->start(s);
1455          _visitor->reach(s);
[100]1456          _list[++_list_back] = s;
[209]1457        }
[100]1458    }
[209]1459
[100]1460    /// \brief Processes the next node.
1461    ///
1462    /// Processes the next node.
1463    ///
1464    /// \return The processed node.
1465    ///
[244]1466    /// \pre The queue must not be empty.
[209]1467    Node processNextNode() {
[100]1468      Node n = _list[++_list_front];
1469      _visitor->process(n);
1470      Arc e;
1471      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1472        Node m = _digraph->target(e);
1473        if (!(*_reached)[m]) {
1474          _visitor->discover(e);
1475          _visitor->reach(m);
1476          _reached->set(m, true);
1477          _list[++_list_back] = m;
1478        } else {
1479          _visitor->examine(e);
1480        }
1481      }
1482      return n;
1483    }
1484
1485    /// \brief Processes the next node.
1486    ///
[244]1487    /// Processes the next node and checks if the given target node
[100]1488    /// is reached. If the target node is reachable from the processed
[244]1489    /// node, then the \c reach parameter will be set to \c true.
[100]1490    ///
1491    /// \param target The target node.
[244]1492    /// \retval reach Indicates if the target node is reached.
1493    /// It should be initially \c false.
1494    ///
[100]1495    /// \return The processed node.
1496    ///
[244]1497    /// \pre The queue must not be empty.
[100]1498    Node processNextNode(Node target, bool& reach) {
1499      Node n = _list[++_list_front];
1500      _visitor->process(n);
1501      Arc e;
1502      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1503        Node m = _digraph->target(e);
1504        if (!(*_reached)[m]) {
1505          _visitor->discover(e);
1506          _visitor->reach(m);
1507          _reached->set(m, true);
1508          _list[++_list_back] = m;
1509          reach = reach || (target == m);
1510        } else {
1511          _visitor->examine(e);
1512        }
1513      }
1514      return n;
1515    }
1516
1517    /// \brief Processes the next node.
1518    ///
[244]1519    /// Processes the next node and checks if at least one of reached
1520    /// nodes has \c true value in the \c nm node map. If one node
1521    /// with \c true value is reachable from the processed node, then the
1522    /// \c rnode parameter will be set to the first of such nodes.
[100]1523    ///
[244]1524    /// \param nm A \c bool (or convertible) node map that indicates the
1525    /// possible targets.
[100]1526    /// \retval rnode The reached target node.
[244]1527    /// It should be initially \c INVALID.
1528    ///
[100]1529    /// \return The processed node.
1530    ///
[244]1531    /// \pre The queue must not be empty.
[100]1532    template <typename NM>
1533    Node processNextNode(const NM& nm, Node& rnode) {
1534      Node n = _list[++_list_front];
1535      _visitor->process(n);
1536      Arc e;
1537      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1538        Node m = _digraph->target(e);
1539        if (!(*_reached)[m]) {
1540          _visitor->discover(e);
1541          _visitor->reach(m);
1542          _reached->set(m, true);
1543          _list[++_list_back] = m;
1544          if (nm[m] && rnode == INVALID) rnode = m;
1545        } else {
1546          _visitor->examine(e);
1547        }
1548      }
1549      return n;
1550    }
1551
[244]1552    /// \brief The next node to be processed.
[100]1553    ///
[244]1554    /// Returns the next node to be processed or \c INVALID if the queue
1555    /// is empty.
1556    Node nextNode() const {
[100]1557      return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1558    }
1559
1560    /// \brief Returns \c false if there are nodes
[244]1561    /// to be processed.
[100]1562    ///
1563    /// Returns \c false if there are nodes
[244]1564    /// to be processed in the queue.
1565    bool emptyQueue() const { return _list_front == _list_back; }
[100]1566
1567    /// \brief Returns the number of the nodes to be processed.
1568    ///
1569    /// Returns the number of the nodes to be processed in the queue.
[244]1570    int queueSize() const { return _list_back - _list_front; }
[209]1571
[100]1572    /// \brief Executes the algorithm.
1573    ///
1574    /// Executes the algorithm.
1575    ///
[244]1576    /// This method runs the %BFS algorithm from the root node(s)
1577    /// in order to compute the shortest path to each node.
1578    ///
1579    /// The algorithm computes
1580    /// - the shortest path tree (forest),
1581    /// - the distance of each node from the root(s).
1582    ///
1583    /// \pre init() must be called and at least one root node should be added
[100]1584    /// with addSource() before using this function.
[244]1585    ///
1586    /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1587    /// \code
1588    ///   while ( !b.emptyQueue() ) {
1589    ///     b.processNextNode();
1590    ///   }
1591    /// \endcode
[100]1592    void start() {
1593      while ( !emptyQueue() ) processNextNode();
1594    }
[209]1595
[244]1596    /// \brief Executes the algorithm until the given target node is reached.
[100]1597    ///
[244]1598    /// Executes the algorithm until the given target node is reached.
[100]1599    ///
[244]1600    /// This method runs the %BFS algorithm from the root node(s)
[286]1601    /// in order to compute the shortest path to \c t.
[244]1602    ///
1603    /// The algorithm computes
[286]1604    /// - the shortest path to \c t,
1605    /// - the distance of \c t from the root(s).
[244]1606    ///
1607    /// \pre init() must be called and at least one root node should be
1608    /// added with addSource() before using this function.
1609    ///
1610    /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1611    /// \code
1612    ///   bool reach = false;
1613    ///   while ( !b.emptyQueue() && !reach ) {
1614    ///     b.processNextNode(t, reach);
1615    ///   }
1616    /// \endcode
[286]1617    void start(Node t) {
[100]1618      bool reach = false;
[286]1619      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
[100]1620    }
[209]1621
[100]1622    /// \brief Executes the algorithm until a condition is met.
1623    ///
1624    /// Executes the algorithm until a condition is met.
1625    ///
[244]1626    /// This method runs the %BFS algorithm from the root node(s) in
1627    /// order to compute the shortest path to a node \c v with
1628    /// <tt>nm[v]</tt> true, if such a node can be found.
[100]1629    ///
[244]1630    /// \param nm must be a bool (or convertible) node map. The
1631    /// algorithm will stop when it reaches a node \c v with
[100]1632    /// <tt>nm[v]</tt> true.
1633    ///
[244]1634    /// \return The reached node \c v with <tt>nm[v]</tt> true or
1635    /// \c INVALID if no such node was found.
1636    ///
1637    /// \pre init() must be called and at least one root node should be
1638    /// added with addSource() before using this function.
1639    ///
1640    /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1641    /// \code
1642    ///   Node rnode = INVALID;
1643    ///   while ( !b.emptyQueue() && rnode == INVALID ) {
1644    ///     b.processNextNode(nm, rnode);
1645    ///   }
1646    ///   return rnode;
1647    /// \endcode
[100]1648    template <typename NM>
1649    Node start(const NM &nm) {
1650      Node rnode = INVALID;
1651      while ( !emptyQueue() && rnode == INVALID ) {
[209]1652        processNextNode(nm, rnode);
[100]1653      }
1654      return rnode;
1655    }
1656
[286]1657    /// \brief Runs the algorithm from the given source node.
[100]1658    ///
[244]1659    /// This method runs the %BFS algorithm from node \c s
1660    /// in order to compute the shortest path to each node.
1661    ///
1662    /// The algorithm computes
1663    /// - the shortest path tree,
1664    /// - the distance of each node from the root.
1665    ///
1666    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
[100]1667    ///\code
1668    ///   b.init();
1669    ///   b.addSource(s);
1670    ///   b.start();
1671    ///\endcode
1672    void run(Node s) {
1673      init();
1674      addSource(s);
1675      start();
1676    }
1677
[286]1678    /// \brief Finds the shortest path between \c s and \c t.
1679    ///
1680    /// This method runs the %BFS algorithm from node \c s
1681    /// in order to compute the shortest path to node \c t
1682    /// (it stops searching when \c t is processed).
1683    ///
1684    /// \return \c true if \c t is reachable form \c s.
1685    ///
1686    /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1687    /// shortcut of the following code.
1688    ///\code
1689    ///   b.init();
1690    ///   b.addSource(s);
1691    ///   b.start(t);
1692    ///\endcode
1693    bool run(Node s,Node t) {
1694      init();
1695      addSource(s);
1696      start(t);
1697      return reached(t);
1698    }
1699
[244]1700    /// \brief Runs the algorithm to visit all nodes in the digraph.
[209]1701    ///
[100]1702    /// This method runs the %BFS algorithm in order to
[244]1703    /// compute the shortest path to each node.
[100]1704    ///
[244]1705    /// The algorithm computes
1706    /// - the shortest path tree (forest),
1707    /// - the distance of each node from the root(s).
1708    ///
1709    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
[100]1710    ///\code
1711    ///  b.init();
[244]1712    ///  for (NodeIt n(gr); n != INVALID; ++n) {
1713    ///    if (!b.reached(n)) {
1714    ///      b.addSource(n);
[100]1715    ///      b.start();
1716    ///    }
1717    ///  }
1718    ///\endcode
1719    void run() {
1720      init();
1721      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1722        if (!reached(it)) {
1723          addSource(it);
1724          start();
1725        }
1726      }
1727    }
[244]1728
[100]1729    ///@}
1730
1731    /// \name Query Functions
[421]1732    /// The results of the BFS algorithm can be obtained using these
[100]1733    /// functions.\n
[421]1734    /// Either \ref run(Node) "run()" or \ref start() should be called
1735    /// before using them.
1736
[100]1737    ///@{
1738
[421]1739    /// \brief Checks if a node is reached from the root(s).
[100]1740    ///
[421]1741    /// Returns \c true if \c v is reached from the root(s).
1742    ///
1743    /// \pre Either \ref run(Node) "run()" or \ref init()
[100]1744    /// must be called before using this function.
[437]1745    bool reached(Node v) const { return (*_reached)[v]; }
[244]1746
[100]1747    ///@}
[244]1748
[100]1749  };
1750
1751} //END OF NAMESPACE LEMON
1752
1753#endif
Note: See TracBrowser for help on using the repository browser.