gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Merge
0 4 0
merge default
1 file changed with 27 insertions and 17 deletions:
↑ Collapse diff ↑
Show white space 24576 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BFS_H
20 20
#define LEMON_BFS_H
21 21

	
22 22
///\ingroup search
23 23
///\file
24 24
///\brief BFS algorithm.
25 25

	
26 26
#include <lemon/list_graph.h>
27 27
#include <lemon/bits/path_dump.h>
28 28
#include <lemon/core.h>
29 29
#include <lemon/error.h>
30 30
#include <lemon/maps.h>
31 31
#include <lemon/path.h>
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  ///Default traits class of Bfs class.
36 36

	
37 37
  ///Default traits class of Bfs class.
38 38
  ///\tparam GR Digraph type.
39 39
  template<class GR>
40 40
  struct BfsDefaultTraits
41 41
  {
42 42
    ///The type of the digraph the algorithm runs on.
43 43
    typedef GR Digraph;
44 44

	
45 45
    ///\brief The type of the map that stores the predecessor
46 46
    ///arcs of the shortest paths.
47 47
    ///
48 48
    ///The type of the map that stores the predecessor
49 49
    ///arcs of the shortest paths.
50 50
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
51 51
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52 52
    ///Instantiates a PredMap.
53 53

	
54 54
    ///This function instantiates a PredMap.
55 55
    ///\param g is the digraph, to which we would like to define the
56 56
    ///PredMap.
57 57
    static PredMap *createPredMap(const Digraph &g)
58 58
    {
59 59
      return new PredMap(g);
60 60
    }
61 61

	
62 62
    ///The type of the map that indicates which nodes are processed.
63 63

	
64 64
    ///The type of the map that indicates which nodes are processed.
65 65
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
66 66
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
67 67
    ///Instantiates a ProcessedMap.
68 68

	
69 69
    ///This function instantiates a ProcessedMap.
70 70
    ///\param g is the digraph, to which
71 71
    ///we would like to define the ProcessedMap
72 72
#ifdef DOXYGEN
73 73
    static ProcessedMap *createProcessedMap(const Digraph &g)
74 74
#else
75 75
    static ProcessedMap *createProcessedMap(const Digraph &)
76 76
#endif
77 77
    {
78 78
      return new ProcessedMap();
79 79
    }
80 80

	
81 81
    ///The type of the map that indicates which nodes are reached.
82 82

	
83
    ///The type of the map that indicates which nodes are reached.
84
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
83
    ///The type of the map that indicates which nodes are reached.///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
85 84
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
86 85
    ///Instantiates a ReachedMap.
87 86

	
88 87
    ///This function instantiates a ReachedMap.
89 88
    ///\param g is the digraph, to which
90 89
    ///we would like to define the ReachedMap.
91 90
    static ReachedMap *createReachedMap(const Digraph &g)
92 91
    {
93 92
      return new ReachedMap(g);
94 93
    }
95 94

	
96 95
    ///The type of the map that stores the distances of the nodes.
97 96

	
98 97
    ///The type of the map that stores the distances of the nodes.
99 98
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
100 99
    typedef typename Digraph::template NodeMap<int> DistMap;
101 100
    ///Instantiates a DistMap.
102 101

	
103 102
    ///This function instantiates a DistMap.
104 103
    ///\param g is the digraph, to which we would like to define the
105 104
    ///DistMap.
106 105
    static DistMap *createDistMap(const Digraph &g)
107 106
    {
108 107
      return new DistMap(g);
109 108
    }
110 109
  };
111 110

	
112 111
  ///%BFS algorithm class.
113 112

	
114 113
  ///\ingroup search
115 114
  ///This class provides an efficient implementation of the %BFS algorithm.
116 115
  ///
117 116
  ///There is also a \ref bfs() "function-type interface" for the BFS
118 117
  ///algorithm, which is convenient in the simplier cases and it can be
119 118
  ///used easier.
120 119
  ///
121 120
  ///\tparam GR The type of the digraph the algorithm runs on.
122 121
  ///The default value is \ref ListDigraph. The value of GR is not used
123 122
  ///directly by \ref Bfs, it is only passed to \ref BfsDefaultTraits.
124 123
  ///\tparam TR Traits class to set various data types used by the algorithm.
125 124
  ///The default traits class is
126 125
  ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
127 126
  ///See \ref BfsDefaultTraits for the documentation of
128 127
  ///a Bfs traits class.
129 128
#ifdef DOXYGEN
130 129
  template <typename GR,
131 130
            typename TR>
132 131
#else
133 132
  template <typename GR=ListDigraph,
134 133
            typename TR=BfsDefaultTraits<GR> >
135 134
#endif
136 135
  class Bfs {
137 136
  public:
138 137

	
139 138
    ///The type of the digraph the algorithm runs on.
140 139
    typedef typename TR::Digraph Digraph;
141 140

	
142 141
    ///\brief The type of the map that stores the predecessor arcs of the
143 142
    ///shortest paths.
144 143
    typedef typename TR::PredMap PredMap;
145 144
    ///The type of the map that stores the distances of the nodes.
146 145
    typedef typename TR::DistMap DistMap;
147 146
    ///The type of the map that indicates which nodes are reached.
148 147
    typedef typename TR::ReachedMap ReachedMap;
149 148
    ///The type of the map that indicates which nodes are processed.
150 149
    typedef typename TR::ProcessedMap ProcessedMap;
151 150
    ///The type of the paths.
152 151
    typedef PredMapPath<Digraph, PredMap> Path;
153 152

	
154 153
    ///The traits class.
155 154
    typedef TR Traits;
156 155

	
157 156
  private:
158 157

	
159 158
    typedef typename Digraph::Node Node;
160 159
    typedef typename Digraph::NodeIt NodeIt;
161 160
    typedef typename Digraph::Arc Arc;
162 161
    typedef typename Digraph::OutArcIt OutArcIt;
163 162

	
164 163
    //Pointer to the underlying digraph.
165 164
    const Digraph *G;
166 165
    //Pointer to the map of predecessor arcs.
167 166
    PredMap *_pred;
168 167
    //Indicates if _pred is locally allocated (true) or not.
169 168
    bool local_pred;
170 169
    //Pointer to the map of distances.
171 170
    DistMap *_dist;
172 171
    //Indicates if _dist is locally allocated (true) or not.
173 172
    bool local_dist;
174 173
    //Pointer to the map of reached status of the nodes.
175 174
    ReachedMap *_reached;
176 175
    //Indicates if _reached is locally allocated (true) or not.
177 176
    bool local_reached;
178 177
    //Pointer to the map of processed status of the nodes.
179 178
    ProcessedMap *_processed;
180 179
    //Indicates if _processed is locally allocated (true) or not.
181 180
    bool local_processed;
182 181

	
183 182
    std::vector<typename Digraph::Node> _queue;
184 183
    int _queue_head,_queue_tail,_queue_next_dist;
185 184
    int _curr_dist;
186 185

	
187 186
    //Creates the maps if necessary.
188 187
    void create_maps()
189 188
    {
190 189
      if(!_pred) {
191 190
        local_pred = true;
192 191
        _pred = Traits::createPredMap(*G);
193 192
      }
194 193
      if(!_dist) {
195 194
        local_dist = true;
196 195
        _dist = Traits::createDistMap(*G);
197 196
      }
198 197
      if(!_reached) {
199 198
        local_reached = true;
200 199
        _reached = Traits::createReachedMap(*G);
201 200
      }
202 201
      if(!_processed) {
203 202
        local_processed = true;
204 203
        _processed = Traits::createProcessedMap(*G);
205 204
      }
206 205
    }
207 206

	
208 207
  protected:
209 208

	
210 209
    Bfs() {}
211 210

	
212 211
  public:
213 212

	
214 213
    typedef Bfs Create;
215 214

	
216 215
    ///\name Named template parameters
217 216

	
218 217
    ///@{
219 218

	
220 219
    template <class T>
221 220
    struct SetPredMapTraits : public Traits {
222 221
      typedef T PredMap;
223 222
      static PredMap *createPredMap(const Digraph &)
224 223
      {
225 224
        LEMON_ASSERT(false, "PredMap is not initialized");
226 225
        return 0; // ignore warnings
227 226
      }
228 227
    };
229 228
    ///\brief \ref named-templ-param "Named parameter" for setting
230 229
    ///PredMap type.
231 230
    ///
232 231
    ///\ref named-templ-param "Named parameter" for setting
233 232
    ///PredMap type.
234 233
    template <class T>
235 234
    struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
236 235
      typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
237 236
    };
238 237

	
239 238
    template <class T>
240 239
    struct SetDistMapTraits : public Traits {
241 240
      typedef T DistMap;
242 241
      static DistMap *createDistMap(const Digraph &)
243 242
      {
244 243
        LEMON_ASSERT(false, "DistMap is not initialized");
245 244
        return 0; // ignore warnings
246 245
      }
247 246
    };
248 247
    ///\brief \ref named-templ-param "Named parameter" for setting
249 248
    ///DistMap type.
250 249
    ///
251 250
    ///\ref named-templ-param "Named parameter" for setting
252 251
    ///DistMap type.
253 252
    template <class T>
254 253
    struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
255 254
      typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
256 255
    };
257 256

	
258 257
    template <class T>
259 258
    struct SetReachedMapTraits : public Traits {
260 259
      typedef T ReachedMap;
261 260
      static ReachedMap *createReachedMap(const Digraph &)
262 261
      {
263 262
        LEMON_ASSERT(false, "ReachedMap is not initialized");
264 263
        return 0; // ignore warnings
265 264
      }
266 265
    };
267 266
    ///\brief \ref named-templ-param "Named parameter" for setting
268 267
    ///ReachedMap type.
269 268
    ///
270 269
    ///\ref named-templ-param "Named parameter" for setting
271 270
    ///ReachedMap type.
272 271
    template <class T>
273 272
    struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
274 273
      typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
275 274
    };
276 275

	
277 276
    template <class T>
278 277
    struct SetProcessedMapTraits : public Traits {
279 278
      typedef T ProcessedMap;
280 279
      static ProcessedMap *createProcessedMap(const Digraph &)
281 280
      {
282 281
        LEMON_ASSERT(false, "ProcessedMap is not initialized");
283 282
        return 0; // ignore warnings
284 283
      }
285 284
    };
286 285
    ///\brief \ref named-templ-param "Named parameter" for setting
287 286
    ///ProcessedMap type.
288 287
    ///
289 288
    ///\ref named-templ-param "Named parameter" for setting
290 289
    ///ProcessedMap type.
291 290
    template <class T>
292 291
    struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
293 292
      typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
294 293
    };
295 294

	
296 295
    struct SetStandardProcessedMapTraits : public Traits {
297 296
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
298 297
      static ProcessedMap *createProcessedMap(const Digraph &g)
299 298
      {
300 299
        return new ProcessedMap(g);
301 300
        return 0; // ignore warnings
302 301
      }
303 302
    };
304 303
    ///\brief \ref named-templ-param "Named parameter" for setting
305 304
    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
306 305
    ///
307 306
    ///\ref named-templ-param "Named parameter" for setting
308 307
    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
309 308
    ///If you don't set it explicitly, it will be automatically allocated.
310 309
    struct SetStandardProcessedMap :
311 310
      public Bfs< Digraph, SetStandardProcessedMapTraits > {
312 311
      typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
313 312
    };
314 313

	
315 314
    ///@}
316 315

	
317 316
  public:
318 317

	
319 318
    ///Constructor.
320 319

	
321 320
    ///Constructor.
322 321
    ///\param g The digraph the algorithm runs on.
323 322
    Bfs(const Digraph &g) :
324 323
      G(&g),
325 324
      _pred(NULL), local_pred(false),
326 325
      _dist(NULL), local_dist(false),
327 326
      _reached(NULL), local_reached(false),
328 327
      _processed(NULL), local_processed(false)
329 328
    { }
330 329

	
331 330
    ///Destructor.
332 331
    ~Bfs()
333 332
    {
334 333
      if(local_pred) delete _pred;
335 334
      if(local_dist) delete _dist;
336 335
      if(local_reached) delete _reached;
337 336
      if(local_processed) delete _processed;
338 337
    }
339 338

	
340 339
    ///Sets the map that stores the predecessor arcs.
341 340

	
342 341
    ///Sets the map that stores the predecessor arcs.
343 342
    ///If you don't use this function before calling \ref run(),
344 343
    ///it will allocate one. The destructor deallocates this
345 344
    ///automatically allocated map, of course.
346 345
    ///\return <tt> (*this) </tt>
347 346
    Bfs &predMap(PredMap &m)
348 347
    {
349 348
      if(local_pred) {
350 349
        delete _pred;
351 350
        local_pred=false;
352 351
      }
353 352
      _pred = &m;
354 353
      return *this;
355 354
    }
356 355

	
357 356
    ///Sets the map that indicates which nodes are reached.
358 357

	
359 358
    ///Sets the map that indicates which nodes are reached.
360 359
    ///If you don't use this function before calling \ref run(),
361 360
    ///it will allocate one. The destructor deallocates this
362 361
    ///automatically allocated map, of course.
363 362
    ///\return <tt> (*this) </tt>
364 363
    Bfs &reachedMap(ReachedMap &m)
365 364
    {
366 365
      if(local_reached) {
367 366
        delete _reached;
368 367
        local_reached=false;
369 368
      }
370 369
      _reached = &m;
371 370
      return *this;
372 371
    }
373 372

	
374 373
    ///Sets the map that indicates which nodes are processed.
375 374

	
376 375
    ///Sets the map that indicates which nodes are processed.
377 376
    ///If you don't use this function before calling \ref run(),
378 377
    ///it will allocate one. The destructor deallocates this
379 378
    ///automatically allocated map, of course.
380 379
    ///\return <tt> (*this) </tt>
381 380
    Bfs &processedMap(ProcessedMap &m)
382 381
    {
383 382
      if(local_processed) {
384 383
        delete _processed;
385 384
        local_processed=false;
386 385
      }
387 386
      _processed = &m;
388 387
      return *this;
389 388
    }
390 389

	
391 390
    ///Sets the map that stores the distances of the nodes.
392 391

	
393 392
    ///Sets the map that stores the distances of the nodes calculated by
394 393
    ///the algorithm.
395 394
    ///If you don't use this function before calling \ref run(),
396 395
    ///it will allocate one. The destructor deallocates this
397 396
    ///automatically allocated map, of course.
398 397
    ///\return <tt> (*this) </tt>
399 398
    Bfs &distMap(DistMap &m)
400 399
    {
401 400
      if(local_dist) {
402 401
        delete _dist;
403 402
        local_dist=false;
404 403
      }
405 404
      _dist = &m;
406 405
      return *this;
407 406
    }
408 407

	
409 408
  public:
410 409

	
411 410
    ///\name Execution control
412 411
    ///The simplest way to execute the algorithm is to use
413 412
    ///one of the member functions called \ref lemon::Bfs::run() "run()".
414 413
    ///\n
415 414
    ///If you need more control on the execution, first you must call
416 415
    ///\ref lemon::Bfs::init() "init()", then you can add several source
417 416
    ///nodes with \ref lemon::Bfs::addSource() "addSource()".
418 417
    ///Finally \ref lemon::Bfs::start() "start()" will perform the
419 418
    ///actual path computation.
420 419

	
421 420
    ///@{
422 421

	
423 422
    ///Initializes the internal data structures.
424 423

	
425 424
    ///Initializes the internal data structures.
426 425
    ///
427 426
    void init()
428 427
    {
429 428
      create_maps();
430 429
      _queue.resize(countNodes(*G));
431 430
      _queue_head=_queue_tail=0;
432 431
      _curr_dist=1;
433 432
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
434 433
        _pred->set(u,INVALID);
435 434
        _reached->set(u,false);
436 435
        _processed->set(u,false);
437 436
      }
438 437
    }
439 438

	
440 439
    ///Adds a new source node.
441 440

	
442 441
    ///Adds a new source node to the set of nodes to be processed.
443 442
    ///
444 443
    void addSource(Node s)
445 444
    {
446 445
      if(!(*_reached)[s])
447 446
        {
448 447
          _reached->set(s,true);
449 448
          _pred->set(s,INVALID);
450 449
          _dist->set(s,0);
451 450
          _queue[_queue_head++]=s;
452 451
          _queue_next_dist=_queue_head;
453 452
        }
454 453
    }
455 454

	
456 455
    ///Processes the next node.
457 456

	
458 457
    ///Processes the next node.
459 458
    ///
460 459
    ///\return The processed node.
461 460
    ///
462 461
    ///\pre The queue must not be empty.
463 462
    Node processNextNode()
464 463
    {
465 464
      if(_queue_tail==_queue_next_dist) {
466 465
        _curr_dist++;
467 466
        _queue_next_dist=_queue_head;
468 467
      }
469 468
      Node n=_queue[_queue_tail++];
470 469
      _processed->set(n,true);
471 470
      Node m;
472 471
      for(OutArcIt e(*G,n);e!=INVALID;++e)
473 472
        if(!(*_reached)[m=G->target(e)]) {
474 473
          _queue[_queue_head++]=m;
475 474
          _reached->set(m,true);
476 475
          _pred->set(m,e);
477 476
          _dist->set(m,_curr_dist);
478 477
        }
479 478
      return n;
480 479
    }
481 480

	
482 481
    ///Processes the next node.
483 482

	
484 483
    ///Processes the next node and checks if the given target node
485 484
    ///is reached. If the target node is reachable from the processed
486 485
    ///node, then the \c reach parameter will be set to \c true.
487 486
    ///
488 487
    ///\param target The target node.
489 488
    ///\retval reach Indicates if the target node is reached.
490 489
    ///It should be initially \c false.
491 490
    ///
492 491
    ///\return The processed node.
493 492
    ///
494 493
    ///\pre The queue must not be empty.
495 494
    Node processNextNode(Node target, bool& reach)
496 495
    {
497 496
      if(_queue_tail==_queue_next_dist) {
498 497
        _curr_dist++;
499 498
        _queue_next_dist=_queue_head;
500 499
      }
501 500
      Node n=_queue[_queue_tail++];
502 501
      _processed->set(n,true);
503 502
      Node m;
504 503
      for(OutArcIt e(*G,n);e!=INVALID;++e)
505 504
        if(!(*_reached)[m=G->target(e)]) {
506 505
          _queue[_queue_head++]=m;
507 506
          _reached->set(m,true);
508 507
          _pred->set(m,e);
509 508
          _dist->set(m,_curr_dist);
510 509
          reach = reach || (target == m);
511 510
        }
512 511
      return n;
513 512
    }
514 513

	
515 514
    ///Processes the next node.
516 515

	
517 516
    ///Processes the next node and checks if at least one of reached
518 517
    ///nodes has \c true value in the \c nm node map. If one node
519 518
    ///with \c true value is reachable from the processed node, then the
520 519
    ///\c rnode parameter will be set to the first of such nodes.
521 520
    ///
522 521
    ///\param nm A \c bool (or convertible) node map that indicates the
523 522
    ///possible targets.
524 523
    ///\retval rnode The reached target node.
525 524
    ///It should be initially \c INVALID.
526 525
    ///
527 526
    ///\return The processed node.
528 527
    ///
529 528
    ///\pre The queue must not be empty.
530 529
    template<class NM>
531 530
    Node processNextNode(const NM& nm, Node& rnode)
532 531
    {
533 532
      if(_queue_tail==_queue_next_dist) {
534 533
        _curr_dist++;
535 534
        _queue_next_dist=_queue_head;
536 535
      }
537 536
      Node n=_queue[_queue_tail++];
538 537
      _processed->set(n,true);
539 538
      Node m;
540 539
      for(OutArcIt e(*G,n);e!=INVALID;++e)
541 540
        if(!(*_reached)[m=G->target(e)]) {
542 541
          _queue[_queue_head++]=m;
543 542
          _reached->set(m,true);
544 543
          _pred->set(m,e);
545 544
          _dist->set(m,_curr_dist);
546 545
          if (nm[m] && rnode == INVALID) rnode = m;
547 546
        }
548 547
      return n;
549 548
    }
550 549

	
551 550
    ///The next node to be processed.
552 551

	
553 552
    ///Returns the next node to be processed or \c INVALID if the queue
554 553
    ///is empty.
555 554
    Node nextNode() const
556 555
    {
557 556
      return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
558 557
    }
559 558

	
560 559
    ///\brief Returns \c false if there are nodes
561 560
    ///to be processed.
562 561
    ///
563 562
    ///Returns \c false if there are nodes
564 563
    ///to be processed in the queue.
565 564
    bool emptyQueue() const { return _queue_tail==_queue_head; }
566 565

	
567 566
    ///Returns the number of the nodes to be processed.
568 567

	
569 568
    ///Returns the number of the nodes to be processed in the queue.
570 569
    int queueSize() const { return _queue_head-_queue_tail; }
571 570

	
572 571
    ///Executes the algorithm.
573 572

	
574 573
    ///Executes the algorithm.
575 574
    ///
576 575
    ///This method runs the %BFS algorithm from the root node(s)
577 576
    ///in order to compute the shortest path to each node.
578 577
    ///
579 578
    ///The algorithm computes
580 579
    ///- the shortest path tree (forest),
581 580
    ///- the distance of each node from the root(s).
582 581
    ///
583 582
    ///\pre init() must be called and at least one root node should be
584 583
    ///added with addSource() before using this function.
585 584
    ///
586 585
    ///\note <tt>b.start()</tt> is just a shortcut of the following code.
587 586
    ///\code
588 587
    ///  while ( !b.emptyQueue() ) {
589 588
    ///    b.processNextNode();
590 589
    ///  }
591 590
    ///\endcode
592 591
    void start()
593 592
    {
594 593
      while ( !emptyQueue() ) processNextNode();
595 594
    }
596 595

	
597 596
    ///Executes the algorithm until the given target node is reached.
598 597

	
599 598
    ///Executes the algorithm until the given target node is reached.
600 599
    ///
601 600
    ///This method runs the %BFS algorithm from the root node(s)
602 601
    ///in order to compute the shortest path to \c t.
603 602
    ///
604 603
    ///The algorithm computes
605 604
    ///- the shortest path to \c t,
606 605
    ///- the distance of \c t from the root(s).
607 606
    ///
608 607
    ///\pre init() must be called and at least one root node should be
609 608
    ///added with addSource() before using this function.
610 609
    ///
611 610
    ///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
612 611
    ///\code
613 612
    ///  bool reach = false;
614 613
    ///  while ( !b.emptyQueue() && !reach ) {
615 614
    ///    b.processNextNode(t, reach);
616 615
    ///  }
617 616
    ///\endcode
618 617
    void start(Node t)
619 618
    {
620 619
      bool reach = false;
621 620
      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
622 621
    }
623 622

	
624 623
    ///Executes the algorithm until a condition is met.
625 624

	
626 625
    ///Executes the algorithm until a condition is met.
627 626
    ///
628 627
    ///This method runs the %BFS algorithm from the root node(s) in
629 628
    ///order to compute the shortest path to a node \c v with
630 629
    /// <tt>nm[v]</tt> true, if such a node can be found.
631 630
    ///
632 631
    ///\param nm A \c bool (or convertible) node map. The algorithm
633 632
    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
634 633
    ///
635 634
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
636 635
    ///\c INVALID if no such node was found.
637 636
    ///
638 637
    ///\pre init() must be called and at least one root node should be
639 638
    ///added with addSource() before using this function.
640 639
    ///
641 640
    ///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
642 641
    ///\code
643 642
    ///  Node rnode = INVALID;
644 643
    ///  while ( !b.emptyQueue() && rnode == INVALID ) {
645 644
    ///    b.processNextNode(nm, rnode);
646 645
    ///  }
647 646
    ///  return rnode;
648 647
    ///\endcode
649 648
    template<class NodeBoolMap>
650 649
    Node start(const NodeBoolMap &nm)
651 650
    {
652 651
      Node rnode = INVALID;
653 652
      while ( !emptyQueue() && rnode == INVALID ) {
654 653
        processNextNode(nm, rnode);
655 654
      }
656 655
      return rnode;
657 656
    }
658 657

	
659 658
    ///Runs the algorithm from the given source node.
660 659

	
661 660
    ///This method runs the %BFS algorithm from node \c s
662 661
    ///in order to compute the shortest path to each node.
663 662
    ///
664 663
    ///The algorithm computes
665 664
    ///- the shortest path tree,
666 665
    ///- the distance of each node from the root.
667 666
    ///
668 667
    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
669 668
    ///\code
670 669
    ///  b.init();
671 670
    ///  b.addSource(s);
672 671
    ///  b.start();
673 672
    ///\endcode
674 673
    void run(Node s) {
675 674
      init();
676 675
      addSource(s);
677 676
      start();
678 677
    }
679 678

	
680 679
    ///Finds the shortest path between \c s and \c t.
681 680

	
682 681
    ///This method runs the %BFS algorithm from node \c s
683 682
    ///in order to compute the shortest path to node \c t
684 683
    ///(it stops searching when \c t is processed).
685 684
    ///
686 685
    ///\return \c true if \c t is reachable form \c s.
687 686
    ///
688 687
    ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
689 688
    ///shortcut of the following code.
690 689
    ///\code
691 690
    ///  b.init();
692 691
    ///  b.addSource(s);
693 692
    ///  b.start(t);
694 693
    ///\endcode
695 694
    bool run(Node s,Node t) {
696 695
      init();
697 696
      addSource(s);
698 697
      start(t);
699 698
      return reached(t);
700 699
    }
701 700

	
702 701
    ///Runs the algorithm to visit all nodes in the digraph.
703 702

	
704 703
    ///This method runs the %BFS algorithm in order to
705 704
    ///compute the shortest path to each node.
706 705
    ///
707 706
    ///The algorithm computes
708 707
    ///- the shortest path tree (forest),
709 708
    ///- the distance of each node from the root(s).
710 709
    ///
711 710
    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
712 711
    ///\code
713 712
    ///  b.init();
714 713
    ///  for (NodeIt n(gr); n != INVALID; ++n) {
715 714
    ///    if (!b.reached(n)) {
716 715
    ///      b.addSource(n);
717 716
    ///      b.start();
718 717
    ///    }
719 718
    ///  }
720 719
    ///\endcode
721 720
    void run() {
722 721
      init();
723 722
      for (NodeIt n(*G); n != INVALID; ++n) {
724 723
        if (!reached(n)) {
725 724
          addSource(n);
726 725
          start();
727 726
        }
728 727
      }
729 728
    }
730 729

	
731 730
    ///@}
732 731

	
733 732
    ///\name Query Functions
734 733
    ///The result of the %BFS algorithm can be obtained using these
735 734
    ///functions.\n
736 735
    ///Either \ref lemon::Bfs::run() "run()" or \ref lemon::Bfs::start()
737 736
    ///"start()" must be called before using them.
738 737

	
739 738
    ///@{
740 739

	
741 740
    ///The shortest path to a node.
742 741

	
743 742
    ///Returns the shortest path to a node.
744 743
    ///
745 744
    ///\warning \c t should be reachable from the root(s).
746 745
    ///
747 746
    ///\pre Either \ref run() or \ref start() must be called before
748 747
    ///using this function.
749 748
    Path path(Node t) const { return Path(*G, *_pred, t); }
750 749

	
751 750
    ///The distance of a node from the root(s).
752 751

	
753 752
    ///Returns the distance of a node from the root(s).
754 753
    ///
755 754
    ///\warning If node \c v is not reachable from the root(s), then
756 755
    ///the return value of this function is undefined.
757 756
    ///
758 757
    ///\pre Either \ref run() or \ref start() must be called before
759 758
    ///using this function.
760 759
    int dist(Node v) const { return (*_dist)[v]; }
761 760

	
762 761
    ///Returns the 'previous arc' of the shortest path tree for a node.
763 762

	
764 763
    ///This function returns the 'previous arc' of the shortest path
765 764
    ///tree for the node \c v, i.e. it returns the last arc of a
766 765
    ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
767 766
    ///is not reachable from the root(s) or if \c v is a root.
768 767
    ///
769 768
    ///The shortest path tree used here is equal to the shortest path
770 769
    ///tree used in \ref predNode().
771 770
    ///
772 771
    ///\pre Either \ref run() or \ref start() must be called before
773 772
    ///using this function.
774 773
    Arc predArc(Node v) const { return (*_pred)[v];}
775 774

	
776 775
    ///Returns the 'previous node' of the shortest path tree for a node.
777 776

	
778 777
    ///This function returns the 'previous node' of the shortest path
779 778
    ///tree for the node \c v, i.e. it returns the last but one node
780 779
    ///from a shortest path from the root(s) to \c v. It is \c INVALID
781 780
    ///if \c v is not reachable from the root(s) or if \c v is a root.
782 781
    ///
783 782
    ///The shortest path tree used here is equal to the shortest path
784 783
    ///tree used in \ref predArc().
785 784
    ///
786 785
    ///\pre Either \ref run() or \ref start() must be called before
787 786
    ///using this function.
788 787
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
789 788
                                  G->source((*_pred)[v]); }
790 789

	
791 790
    ///\brief Returns a const reference to the node map that stores the
792 791
    /// distances of the nodes.
793 792
    ///
794 793
    ///Returns a const reference to the node map that stores the distances
795 794
    ///of the nodes calculated by the algorithm.
796 795
    ///
797 796
    ///\pre Either \ref run() or \ref init()
798 797
    ///must be called before using this function.
799 798
    const DistMap &distMap() const { return *_dist;}
800 799

	
801 800
    ///\brief Returns a const reference to the node map that stores the
802 801
    ///predecessor arcs.
803 802
    ///
804 803
    ///Returns a const reference to the node map that stores the predecessor
805 804
    ///arcs, which form the shortest path tree.
806 805
    ///
807 806
    ///\pre Either \ref run() or \ref init()
808 807
    ///must be called before using this function.
809 808
    const PredMap &predMap() const { return *_pred;}
810 809

	
811 810
    ///Checks if a node is reachable from the root(s).
812 811

	
813 812
    ///Returns \c true if \c v is reachable from the root(s).
814 813
    ///\pre Either \ref run() or \ref start()
815 814
    ///must be called before using this function.
816 815
    bool reached(Node v) const { return (*_reached)[v]; }
817 816

	
818 817
    ///@}
819 818
  };
820 819

	
821 820
  ///Default traits class of bfs() function.
822 821

	
823 822
  ///Default traits class of bfs() function.
824 823
  ///\tparam GR Digraph type.
825 824
  template<class GR>
826 825
  struct BfsWizardDefaultTraits
827 826
  {
828 827
    ///The type of the digraph the algorithm runs on.
829 828
    typedef GR Digraph;
830 829

	
831 830
    ///\brief The type of the map that stores the predecessor
832 831
    ///arcs of the shortest paths.
833 832
    ///
834 833
    ///The type of the map that stores the predecessor
835 834
    ///arcs of the shortest paths.
836 835
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
837 836
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
838 837
    ///Instantiates a PredMap.
839 838

	
840 839
    ///This function instantiates a PredMap.
841 840
    ///\param g is the digraph, to which we would like to define the
842 841
    ///PredMap.
843 842
    static PredMap *createPredMap(const Digraph &g)
844 843
    {
845 844
      return new PredMap(g);
846 845
    }
847 846

	
848 847
    ///The type of the map that indicates which nodes are processed.
849 848

	
850 849
    ///The type of the map that indicates which nodes are processed.
851 850
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
852 851
    ///By default it is a NullMap.
853 852
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
854 853
    ///Instantiates a ProcessedMap.
855 854

	
856 855
    ///This function instantiates a ProcessedMap.
857 856
    ///\param g is the digraph, to which
858 857
    ///we would like to define the ProcessedMap.
859 858
#ifdef DOXYGEN
860 859
    static ProcessedMap *createProcessedMap(const Digraph &g)
861 860
#else
862 861
    static ProcessedMap *createProcessedMap(const Digraph &)
863 862
#endif
864 863
    {
865 864
      return new ProcessedMap();
866 865
    }
867 866

	
868 867
    ///The type of the map that indicates which nodes are reached.
869 868

	
870 869
    ///The type of the map that indicates which nodes are reached.
871 870
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
872 871
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
873 872
    ///Instantiates a ReachedMap.
874 873

	
875 874
    ///This function instantiates a ReachedMap.
876 875
    ///\param g is the digraph, to which
877 876
    ///we would like to define the ReachedMap.
878 877
    static ReachedMap *createReachedMap(const Digraph &g)
879 878
    {
880 879
      return new ReachedMap(g);
881 880
    }
882 881

	
883 882
    ///The type of the map that stores the distances of the nodes.
884 883

	
885 884
    ///The type of the map that stores the distances of the nodes.
886 885
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
887 886
    typedef typename Digraph::template NodeMap<int> DistMap;
888 887
    ///Instantiates a DistMap.
889 888

	
890 889
    ///This function instantiates a DistMap.
891 890
    ///\param g is the digraph, to which we would like to define
892 891
    ///the DistMap
893 892
    static DistMap *createDistMap(const Digraph &g)
894 893
    {
895 894
      return new DistMap(g);
896 895
    }
897 896

	
898 897
    ///The type of the shortest paths.
899 898

	
900 899
    ///The type of the shortest paths.
901 900
    ///It must meet the \ref concepts::Path "Path" concept.
902 901
    typedef lemon::Path<Digraph> Path;
903 902
  };
904 903

	
905 904
  /// Default traits class used by BfsWizard
906 905

	
907 906
  /// To make it easier to use Bfs algorithm
908 907
  /// we have created a wizard class.
909 908
  /// This \ref BfsWizard class needs default traits,
910 909
  /// as well as the \ref Bfs class.
911 910
  /// The \ref BfsWizardBase is a class to be the default traits of the
912 911
  /// \ref BfsWizard class.
913 912
  template<class GR>
914 913
  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
915 914
  {
916 915

	
917 916
    typedef BfsWizardDefaultTraits<GR> Base;
918 917
  protected:
919 918
    //The type of the nodes in the digraph.
920 919
    typedef typename Base::Digraph::Node Node;
921 920

	
922 921
    //Pointer to the digraph the algorithm runs on.
923 922
    void *_g;
924 923
    //Pointer to the map of reached nodes.
925 924
    void *_reached;
926 925
    //Pointer to the map of processed nodes.
927 926
    void *_processed;
928 927
    //Pointer to the map of predecessors arcs.
929 928
    void *_pred;
930 929
    //Pointer to the map of distances.
931 930
    void *_dist;
932 931
    //Pointer to the shortest path to the target node.
933 932
    void *_path;
934 933
    //Pointer to the distance of the target node.
935 934
    int *_di;
936 935

	
937 936
    public:
938 937
    /// Constructor.
939 938

	
940 939
    /// This constructor does not require parameters, therefore it initiates
941 940
    /// all of the attributes to \c 0.
942 941
    BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
943 942
                      _dist(0), _path(0), _di(0) {}
944 943

	
945 944
    /// Constructor.
946 945

	
947 946
    /// This constructor requires one parameter,
948 947
    /// others are initiated to \c 0.
949 948
    /// \param g The digraph the algorithm runs on.
950 949
    BfsWizardBase(const GR &g) :
951 950
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
952 951
      _reached(0), _processed(0), _pred(0), _dist(0),  _path(0), _di(0) {}
953 952

	
954 953
  };
955 954

	
956 955
  /// Auxiliary class for the function-type interface of BFS algorithm.
957 956

	
958 957
  /// This auxiliary class is created to implement the
959 958
  /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
960 959
  /// It does not have own \ref run() method, it uses the functions
961 960
  /// and features of the plain \ref Bfs.
962 961
  ///
963 962
  /// This class should only be used through the \ref bfs() function,
964 963
  /// which makes it easier to use the algorithm.
965 964
  template<class TR>
966 965
  class BfsWizard : public TR
967 966
  {
968 967
    typedef TR Base;
969 968

	
970 969
    ///The type of the digraph the algorithm runs on.
971 970
    typedef typename TR::Digraph Digraph;
972 971

	
973 972
    typedef typename Digraph::Node Node;
974 973
    typedef typename Digraph::NodeIt NodeIt;
975 974
    typedef typename Digraph::Arc Arc;
976 975
    typedef typename Digraph::OutArcIt OutArcIt;
977 976

	
978 977
    ///\brief The type of the map that stores the predecessor
979 978
    ///arcs of the shortest paths.
980 979
    typedef typename TR::PredMap PredMap;
981 980
    ///\brief The type of the map that stores the distances of the nodes.
982 981
    typedef typename TR::DistMap DistMap;
983 982
    ///\brief The type of the map that indicates which nodes are reached.
984 983
    typedef typename TR::ReachedMap ReachedMap;
985 984
    ///\brief The type of the map that indicates which nodes are processed.
986 985
    typedef typename TR::ProcessedMap ProcessedMap;
987 986
    ///The type of the shortest paths
988 987
    typedef typename TR::Path Path;
989 988

	
990 989
  public:
991 990

	
992 991
    /// Constructor.
993 992
    BfsWizard() : TR() {}
994 993

	
995 994
    /// Constructor that requires parameters.
996 995

	
997 996
    /// Constructor that requires parameters.
998 997
    /// These parameters will be the default values for the traits class.
999 998
    /// \param g The digraph the algorithm runs on.
1000 999
    BfsWizard(const Digraph &g) :
1001 1000
      TR(g) {}
1002 1001

	
1003 1002
    ///Copy constructor
1004 1003
    BfsWizard(const TR &b) : TR(b) {}
1005 1004

	
1006 1005
    ~BfsWizard() {}
1007 1006

	
1008 1007
    ///Runs BFS algorithm from the given source node.
1009 1008

	
1010 1009
    ///This method runs BFS algorithm from node \c s
1011 1010
    ///in order to compute the shortest path to each node.
1012 1011
    void run(Node s)
1013 1012
    {
1014 1013
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1015 1014
      if (Base::_pred)
1016 1015
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1017 1016
      if (Base::_dist)
1018 1017
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1019 1018
      if (Base::_reached)
1020 1019
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1021 1020
      if (Base::_processed)
1022 1021
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1023 1022
      if (s!=INVALID)
1024 1023
        alg.run(s);
1025 1024
      else
1026 1025
        alg.run();
1027 1026
    }
1028 1027

	
1029 1028
    ///Finds the shortest path between \c s and \c t.
1030 1029

	
1031 1030
    ///This method runs BFS algorithm from node \c s
1032 1031
    ///in order to compute the shortest path to node \c t
1033 1032
    ///(it stops searching when \c t is processed).
1034 1033
    ///
1035 1034
    ///\return \c true if \c t is reachable form \c s.
1036 1035
    bool run(Node s, Node t)
1037 1036
    {
1038 1037
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1039 1038
      if (Base::_pred)
1040 1039
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1041 1040
      if (Base::_dist)
1042 1041
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1043 1042
      if (Base::_reached)
1044 1043
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1045 1044
      if (Base::_processed)
1046 1045
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1047 1046
      alg.run(s,t);
1048 1047
      if (Base::_path)
1049 1048
        *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1050 1049
      if (Base::_di)
1051 1050
        *Base::_di = alg.dist(t);
1052 1051
      return alg.reached(t);
1053 1052
    }
1054 1053

	
1055 1054
    ///Runs BFS algorithm to visit all nodes in the digraph.
1056 1055

	
1057 1056
    ///This method runs BFS algorithm in order to compute
1058 1057
    ///the shortest path to each node.
1059 1058
    void run()
1060 1059
    {
1061 1060
      run(INVALID);
1062 1061
    }
1063 1062

	
1064 1063
    template<class T>
1065 1064
    struct SetPredMapBase : public Base {
1066 1065
      typedef T PredMap;
1067 1066
      static PredMap *createPredMap(const Digraph &) { return 0; };
1068 1067
      SetPredMapBase(const TR &b) : TR(b) {}
1069 1068
    };
1070 1069
    ///\brief \ref named-func-param "Named parameter"
1071 1070
    ///for setting PredMap object.
1072 1071
    ///
1073 1072
    ///\ref named-func-param "Named parameter"
1074 1073
    ///for setting PredMap object.
1075 1074
    template<class T>
1076 1075
    BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1077 1076
    {
1078 1077
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1079 1078
      return BfsWizard<SetPredMapBase<T> >(*this);
1080 1079
    }
1081 1080

	
1082 1081
    template<class T>
1083 1082
    struct SetReachedMapBase : public Base {
1084 1083
      typedef T ReachedMap;
1085 1084
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1086 1085
      SetReachedMapBase(const TR &b) : TR(b) {}
1087 1086
    };
1088 1087
    ///\brief \ref named-func-param "Named parameter"
1089 1088
    ///for setting ReachedMap object.
1090 1089
    ///
1091 1090
    /// \ref named-func-param "Named parameter"
1092 1091
    ///for setting ReachedMap object.
1093 1092
    template<class T>
1094 1093
    BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1095 1094
    {
1096 1095
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1097 1096
      return BfsWizard<SetReachedMapBase<T> >(*this);
1098 1097
    }
1099 1098

	
1100 1099
    template<class T>
1101 1100
    struct SetDistMapBase : public Base {
1102 1101
      typedef T DistMap;
1103 1102
      static DistMap *createDistMap(const Digraph &) { return 0; };
1104 1103
      SetDistMapBase(const TR &b) : TR(b) {}
1105 1104
    };
1106 1105
    ///\brief \ref named-func-param "Named parameter"
1107 1106
    ///for setting DistMap object.
1108 1107
    ///
1109 1108
    /// \ref named-func-param "Named parameter"
1110 1109
    ///for setting DistMap object.
1111 1110
    template<class T>
1112 1111
    BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1113 1112
    {
1114 1113
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1115 1114
      return BfsWizard<SetDistMapBase<T> >(*this);
1116 1115
    }
1117 1116

	
1118 1117
    template<class T>
1119 1118
    struct SetProcessedMapBase : public Base {
1120 1119
      typedef T ProcessedMap;
1121 1120
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1122 1121
      SetProcessedMapBase(const TR &b) : TR(b) {}
1123 1122
    };
1124 1123
    ///\brief \ref named-func-param "Named parameter"
1125 1124
    ///for setting ProcessedMap object.
1126 1125
    ///
1127 1126
    /// \ref named-func-param "Named parameter"
1128 1127
    ///for setting ProcessedMap object.
1129 1128
    template<class T>
1130 1129
    BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1131 1130
    {
1132 1131
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1133 1132
      return BfsWizard<SetProcessedMapBase<T> >(*this);
1134 1133
    }
1135 1134

	
1136 1135
    template<class T>
1137 1136
    struct SetPathBase : public Base {
1138 1137
      typedef T Path;
1139 1138
      SetPathBase(const TR &b) : TR(b) {}
1140 1139
    };
1141 1140
    ///\brief \ref named-func-param "Named parameter"
1142 1141
    ///for getting the shortest path to the target node.
1143 1142
    ///
1144 1143
    ///\ref named-func-param "Named parameter"
1145 1144
    ///for getting the shortest path to the target node.
1146 1145
    template<class T>
1147 1146
    BfsWizard<SetPathBase<T> > path(const T &t)
1148 1147
    {
1149 1148
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1150 1149
      return BfsWizard<SetPathBase<T> >(*this);
1151 1150
    }
1152 1151

	
1153 1152
    ///\brief \ref named-func-param "Named parameter"
1154 1153
    ///for getting the distance of the target node.
1155 1154
    ///
1156 1155
    ///\ref named-func-param "Named parameter"
1157 1156
    ///for getting the distance of the target node.
1158 1157
    BfsWizard dist(const int &d)
1159 1158
    {
1160 1159
      Base::_di=const_cast<int*>(&d);
1161 1160
      return *this;
1162 1161
    }
1163 1162

	
1164 1163
  };
1165 1164

	
1166 1165
  ///Function-type interface for BFS algorithm.
1167 1166

	
1168 1167
  /// \ingroup search
1169 1168
  ///Function-type interface for BFS algorithm.
1170 1169
  ///
1171 1170
  ///This function also has several \ref named-func-param "named parameters",
1172 1171
  ///they are declared as the members of class \ref BfsWizard.
1173 1172
  ///The following examples show how to use these parameters.
1174 1173
  ///\code
1175 1174
  ///  // Compute shortest path from node s to each node
1176 1175
  ///  bfs(g).predMap(preds).distMap(dists).run(s);
1177 1176
  ///
1178 1177
  ///  // Compute shortest path from s to t
1179 1178
  ///  bool reached = bfs(g).path(p).dist(d).run(s,t);
1180 1179
  ///\endcode
1181 1180
  ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1182 1181
  ///to the end of the parameter list.
1183 1182
  ///\sa BfsWizard
1184 1183
  ///\sa Bfs
1185 1184
  template<class GR>
1186 1185
  BfsWizard<BfsWizardBase<GR> >
1187 1186
  bfs(const GR &digraph)
1188 1187
  {
1189 1188
    return BfsWizard<BfsWizardBase<GR> >(digraph);
1190 1189
  }
1191 1190

	
1192 1191
#ifdef DOXYGEN
1193 1192
  /// \brief Visitor class for BFS.
1194 1193
  ///
1195 1194
  /// This class defines the interface of the BfsVisit events, and
1196 1195
  /// it could be the base of a real visitor class.
1197 1196
  template <typename _Digraph>
1198 1197
  struct BfsVisitor {
1199 1198
    typedef _Digraph Digraph;
1200 1199
    typedef typename Digraph::Arc Arc;
1201 1200
    typedef typename Digraph::Node Node;
1202 1201
    /// \brief Called for the source node(s) of the BFS.
1203 1202
    ///
1204 1203
    /// This function is called for the source node(s) of the BFS.
1205 1204
    void start(const Node& node) {}
1206 1205
    /// \brief Called when a node is reached first time.
1207 1206
    ///
1208 1207
    /// This function is called when a node is reached first time.
1209 1208
    void reach(const Node& node) {}
1210 1209
    /// \brief Called when a node is processed.
1211 1210
    ///
1212 1211
    /// This function is called when a node is processed.
1213 1212
    void process(const Node& node) {}
1214 1213
    /// \brief Called when an arc reaches a new node.
1215 1214
    ///
1216 1215
    /// This function is called when the BFS finds an arc whose target node
1217 1216
    /// is not reached yet.
1218 1217
    void discover(const Arc& arc) {}
1219 1218
    /// \brief Called when an arc is examined but its target node is
1220 1219
    /// already discovered.
1221 1220
    ///
1222 1221
    /// This function is called when an arc is examined but its target node is
1223 1222
    /// already discovered.
1224 1223
    void examine(const Arc& arc) {}
1225 1224
  };
1226 1225
#else
1227 1226
  template <typename _Digraph>
1228 1227
  struct BfsVisitor {
1229 1228
    typedef _Digraph Digraph;
1230 1229
    typedef typename Digraph::Arc Arc;
1231 1230
    typedef typename Digraph::Node Node;
1232 1231
    void start(const Node&) {}
1233 1232
    void reach(const Node&) {}
1234 1233
    void process(const Node&) {}
1235 1234
    void discover(const Arc&) {}
1236 1235
    void examine(const Arc&) {}
1237 1236

	
1238 1237
    template <typename _Visitor>
1239 1238
    struct Constraints {
1240 1239
      void constraints() {
1241 1240
        Arc arc;
1242 1241
        Node node;
1243 1242
        visitor.start(node);
1244 1243
        visitor.reach(node);
1245 1244
        visitor.process(node);
1246 1245
        visitor.discover(arc);
1247 1246
        visitor.examine(arc);
1248 1247
      }
1249 1248
      _Visitor& visitor;
1250 1249
    };
1251 1250
  };
1252 1251
#endif
1253 1252

	
1254 1253
  /// \brief Default traits class of BfsVisit class.
1255 1254
  ///
1256 1255
  /// Default traits class of BfsVisit class.
1257 1256
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1258 1257
  template<class _Digraph>
1259 1258
  struct BfsVisitDefaultTraits {
1260 1259

	
1261 1260
    /// \brief The type of the digraph the algorithm runs on.
1262 1261
    typedef _Digraph Digraph;
1263 1262

	
1264 1263
    /// \brief The type of the map that indicates which nodes are reached.
1265 1264
    ///
1266 1265
    /// The type of the map that indicates which nodes are reached.
1267 1266
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1268 1267
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1269 1268

	
1270 1269
    /// \brief Instantiates a ReachedMap.
1271 1270
    ///
1272 1271
    /// This function instantiates a ReachedMap.
1273 1272
    /// \param digraph is the digraph, to which
1274 1273
    /// we would like to define the ReachedMap.
1275 1274
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1276 1275
      return new ReachedMap(digraph);
1277 1276
    }
1278 1277

	
1279 1278
  };
1280 1279

	
1281 1280
  /// \ingroup search
1282 1281
  ///
1283 1282
  /// \brief %BFS algorithm class with visitor interface.
1284 1283
  ///
1285 1284
  /// This class provides an efficient implementation of the %BFS algorithm
1286 1285
  /// with visitor interface.
1287 1286
  ///
1288 1287
  /// The %BfsVisit class provides an alternative interface to the Bfs
1289 1288
  /// class. It works with callback mechanism, the BfsVisit object calls
1290 1289
  /// the member functions of the \c Visitor class on every BFS event.
1291 1290
  ///
1292 1291
  /// This interface of the BFS algorithm should be used in special cases
1293 1292
  /// when extra actions have to be performed in connection with certain
1294 1293
  /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1295 1294
  /// instead.
1296 1295
  ///
1297 1296
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1298 1297
  /// The default value is
1299 1298
  /// \ref ListDigraph. The value of _Digraph is not used directly by
1300 1299
  /// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits.
1301 1300
  /// \tparam _Visitor The Visitor type that is used by the algorithm.
1302 1301
  /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which
1303 1302
  /// does not observe the BFS events. If you want to observe the BFS
1304 1303
  /// events, you should implement your own visitor class.
1305 1304
  /// \tparam _Traits Traits class to set various data types used by the
1306 1305
  /// algorithm. The default traits class is
1307 1306
  /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
1308 1307
  /// See \ref BfsVisitDefaultTraits for the documentation of
1309 1308
  /// a BFS visit traits class.
1310 1309
#ifdef DOXYGEN
1311 1310
  template <typename _Digraph, typename _Visitor, typename _Traits>
1312 1311
#else
1313 1312
  template <typename _Digraph = ListDigraph,
1314 1313
            typename _Visitor = BfsVisitor<_Digraph>,
1315 1314
            typename _Traits = BfsVisitDefaultTraits<_Digraph> >
1316 1315
#endif
1317 1316
  class BfsVisit {
1318 1317
  public:
1319 1318

	
1320 1319
    ///The traits class.
1321 1320
    typedef _Traits Traits;
1322 1321

	
1323 1322
    ///The type of the digraph the algorithm runs on.
1324 1323
    typedef typename Traits::Digraph Digraph;
1325 1324

	
1326 1325
    ///The visitor type used by the algorithm.
1327 1326
    typedef _Visitor Visitor;
1328 1327

	
1329 1328
    ///The type of the map that indicates which nodes are reached.
1330 1329
    typedef typename Traits::ReachedMap ReachedMap;
1331 1330

	
1332 1331
  private:
1333 1332

	
1334 1333
    typedef typename Digraph::Node Node;
1335 1334
    typedef typename Digraph::NodeIt NodeIt;
1336 1335
    typedef typename Digraph::Arc Arc;
1337 1336
    typedef typename Digraph::OutArcIt OutArcIt;
1338 1337

	
1339 1338
    //Pointer to the underlying digraph.
1340 1339
    const Digraph *_digraph;
1341 1340
    //Pointer to the visitor object.
1342 1341
    Visitor *_visitor;
1343 1342
    //Pointer to the map of reached status of the nodes.
1344 1343
    ReachedMap *_reached;
1345 1344
    //Indicates if _reached is locally allocated (true) or not.
1346 1345
    bool local_reached;
1347 1346

	
1348 1347
    std::vector<typename Digraph::Node> _list;
1349 1348
    int _list_front, _list_back;
1350 1349

	
1351 1350
    //Creates the maps if necessary.
1352 1351
    void create_maps() {
1353 1352
      if(!_reached) {
1354 1353
        local_reached = true;
1355 1354
        _reached = Traits::createReachedMap(*_digraph);
1356 1355
      }
1357 1356
    }
1358 1357

	
1359 1358
  protected:
1360 1359

	
1361 1360
    BfsVisit() {}
1362 1361

	
1363 1362
  public:
1364 1363

	
1365 1364
    typedef BfsVisit Create;
1366 1365

	
1367 1366
    /// \name Named template parameters
1368 1367

	
1369 1368
    ///@{
1370 1369
    template <class T>
1371 1370
    struct SetReachedMapTraits : public Traits {
1372 1371
      typedef T ReachedMap;
1373 1372
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1374 1373
        LEMON_ASSERT(false, "ReachedMap is not initialized");
1375 1374
        return 0; // ignore warnings
1376 1375
      }
1377 1376
    };
1378 1377
    /// \brief \ref named-templ-param "Named parameter" for setting
1379 1378
    /// ReachedMap type.
1380 1379
    ///
1381 1380
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1382 1381
    template <class T>
1383 1382
    struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1384 1383
                                            SetReachedMapTraits<T> > {
1385 1384
      typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1386 1385
    };
1387 1386
    ///@}
1388 1387

	
1389 1388
  public:
1390 1389

	
1391 1390
    /// \brief Constructor.
1392 1391
    ///
1393 1392
    /// Constructor.
1394 1393
    ///
1395 1394
    /// \param digraph The digraph the algorithm runs on.
1396 1395
    /// \param visitor The visitor object of the algorithm.
1397 1396
    BfsVisit(const Digraph& digraph, Visitor& visitor)
1398 1397
      : _digraph(&digraph), _visitor(&visitor),
1399 1398
        _reached(0), local_reached(false) {}
1400 1399

	
1401 1400
    /// \brief Destructor.
1402 1401
    ~BfsVisit() {
1403 1402
      if(local_reached) delete _reached;
1404 1403
    }
1405 1404

	
1406 1405
    /// \brief Sets the map that indicates which nodes are reached.
1407 1406
    ///
1408 1407
    /// Sets the map that indicates which nodes are reached.
1409 1408
    /// If you don't use this function before calling \ref run(),
1410 1409
    /// it will allocate one. The destructor deallocates this
1411 1410
    /// automatically allocated map, of course.
1412 1411
    /// \return <tt> (*this) </tt>
1413 1412
    BfsVisit &reachedMap(ReachedMap &m) {
1414 1413
      if(local_reached) {
1415 1414
        delete _reached;
1416 1415
        local_reached = false;
1417 1416
      }
1418 1417
      _reached = &m;
1419 1418
      return *this;
1420 1419
    }
1421 1420

	
1422 1421
  public:
1423 1422

	
1424 1423
    /// \name Execution control
1425 1424
    /// The simplest way to execute the algorithm is to use
1426 1425
    /// one of the member functions called \ref lemon::BfsVisit::run()
1427 1426
    /// "run()".
1428 1427
    /// \n
1429 1428
    /// If you need more control on the execution, first you must call
1430 1429
    /// \ref lemon::BfsVisit::init() "init()", then you can add several
1431 1430
    /// source nodes with \ref lemon::BfsVisit::addSource() "addSource()".
1432 1431
    /// Finally \ref lemon::BfsVisit::start() "start()" will perform the
1433 1432
    /// actual path computation.
1434 1433

	
1435 1434
    /// @{
1436 1435

	
1437 1436
    /// \brief Initializes the internal data structures.
1438 1437
    ///
1439 1438
    /// Initializes the internal data structures.
1440 1439
    void init() {
1441 1440
      create_maps();
1442 1441
      _list.resize(countNodes(*_digraph));
1443 1442
      _list_front = _list_back = -1;
1444 1443
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1445 1444
        _reached->set(u, false);
1446 1445
      }
1447 1446
    }
1448 1447

	
1449 1448
    /// \brief Adds a new source node.
1450 1449
    ///
1451 1450
    /// Adds a new source node to the set of nodes to be processed.
1452 1451
    void addSource(Node s) {
1453 1452
      if(!(*_reached)[s]) {
1454 1453
          _reached->set(s,true);
1455 1454
          _visitor->start(s);
1456 1455
          _visitor->reach(s);
1457 1456
          _list[++_list_back] = s;
1458 1457
        }
1459 1458
    }
1460 1459

	
1461 1460
    /// \brief Processes the next node.
1462 1461
    ///
1463 1462
    /// Processes the next node.
1464 1463
    ///
1465 1464
    /// \return The processed node.
1466 1465
    ///
1467 1466
    /// \pre The queue must not be empty.
1468 1467
    Node processNextNode() {
1469 1468
      Node n = _list[++_list_front];
1470 1469
      _visitor->process(n);
1471 1470
      Arc e;
1472 1471
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1473 1472
        Node m = _digraph->target(e);
1474 1473
        if (!(*_reached)[m]) {
1475 1474
          _visitor->discover(e);
1476 1475
          _visitor->reach(m);
1477 1476
          _reached->set(m, true);
1478 1477
          _list[++_list_back] = m;
1479 1478
        } else {
1480 1479
          _visitor->examine(e);
1481 1480
        }
1482 1481
      }
1483 1482
      return n;
1484 1483
    }
1485 1484

	
1486 1485
    /// \brief Processes the next node.
1487 1486
    ///
1488 1487
    /// Processes the next node and checks if the given target node
1489 1488
    /// is reached. If the target node is reachable from the processed
1490 1489
    /// node, then the \c reach parameter will be set to \c true.
1491 1490
    ///
1492 1491
    /// \param target The target node.
1493 1492
    /// \retval reach Indicates if the target node is reached.
1494 1493
    /// It should be initially \c false.
1495 1494
    ///
1496 1495
    /// \return The processed node.
1497 1496
    ///
1498 1497
    /// \pre The queue must not be empty.
1499 1498
    Node processNextNode(Node target, bool& reach) {
1500 1499
      Node n = _list[++_list_front];
1501 1500
      _visitor->process(n);
1502 1501
      Arc e;
1503 1502
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1504 1503
        Node m = _digraph->target(e);
1505 1504
        if (!(*_reached)[m]) {
1506 1505
          _visitor->discover(e);
1507 1506
          _visitor->reach(m);
1508 1507
          _reached->set(m, true);
1509 1508
          _list[++_list_back] = m;
1510 1509
          reach = reach || (target == m);
1511 1510
        } else {
1512 1511
          _visitor->examine(e);
1513 1512
        }
1514 1513
      }
1515 1514
      return n;
1516 1515
    }
1517 1516

	
1518 1517
    /// \brief Processes the next node.
1519 1518
    ///
1520 1519
    /// Processes the next node and checks if at least one of reached
1521 1520
    /// nodes has \c true value in the \c nm node map. If one node
1522 1521
    /// with \c true value is reachable from the processed node, then the
1523 1522
    /// \c rnode parameter will be set to the first of such nodes.
1524 1523
    ///
1525 1524
    /// \param nm A \c bool (or convertible) node map that indicates the
1526 1525
    /// possible targets.
1527 1526
    /// \retval rnode The reached target node.
1528 1527
    /// It should be initially \c INVALID.
1529 1528
    ///
1530 1529
    /// \return The processed node.
1531 1530
    ///
1532 1531
    /// \pre The queue must not be empty.
1533 1532
    template <typename NM>
1534 1533
    Node processNextNode(const NM& nm, Node& rnode) {
1535 1534
      Node n = _list[++_list_front];
1536 1535
      _visitor->process(n);
1537 1536
      Arc e;
1538 1537
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1539 1538
        Node m = _digraph->target(e);
1540 1539
        if (!(*_reached)[m]) {
1541 1540
          _visitor->discover(e);
1542 1541
          _visitor->reach(m);
1543 1542
          _reached->set(m, true);
1544 1543
          _list[++_list_back] = m;
1545 1544
          if (nm[m] && rnode == INVALID) rnode = m;
1546 1545
        } else {
1547 1546
          _visitor->examine(e);
1548 1547
        }
1549 1548
      }
1550 1549
      return n;
1551 1550
    }
1552 1551

	
1553 1552
    /// \brief The next node to be processed.
1554 1553
    ///
1555 1554
    /// Returns the next node to be processed or \c INVALID if the queue
1556 1555
    /// is empty.
1557 1556
    Node nextNode() const {
1558 1557
      return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1559 1558
    }
1560 1559

	
1561 1560
    /// \brief Returns \c false if there are nodes
1562 1561
    /// to be processed.
1563 1562
    ///
1564 1563
    /// Returns \c false if there are nodes
1565 1564
    /// to be processed in the queue.
1566 1565
    bool emptyQueue() const { return _list_front == _list_back; }
1567 1566

	
1568 1567
    /// \brief Returns the number of the nodes to be processed.
1569 1568
    ///
1570 1569
    /// Returns the number of the nodes to be processed in the queue.
1571 1570
    int queueSize() const { return _list_back - _list_front; }
1572 1571

	
1573 1572
    /// \brief Executes the algorithm.
1574 1573
    ///
1575 1574
    /// Executes the algorithm.
1576 1575
    ///
1577 1576
    /// This method runs the %BFS algorithm from the root node(s)
1578 1577
    /// in order to compute the shortest path to each node.
1579 1578
    ///
1580 1579
    /// The algorithm computes
1581 1580
    /// - the shortest path tree (forest),
1582 1581
    /// - the distance of each node from the root(s).
1583 1582
    ///
1584 1583
    /// \pre init() must be called and at least one root node should be added
1585 1584
    /// with addSource() before using this function.
1586 1585
    ///
1587 1586
    /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1588 1587
    /// \code
1589 1588
    ///   while ( !b.emptyQueue() ) {
1590 1589
    ///     b.processNextNode();
1591 1590
    ///   }
1592 1591
    /// \endcode
1593 1592
    void start() {
1594 1593
      while ( !emptyQueue() ) processNextNode();
1595 1594
    }
1596 1595

	
1597 1596
    /// \brief Executes the algorithm until the given target node is reached.
1598 1597
    ///
1599 1598
    /// Executes the algorithm until the given target node is reached.
1600 1599
    ///
1601 1600
    /// This method runs the %BFS algorithm from the root node(s)
1602 1601
    /// in order to compute the shortest path to \c t.
1603 1602
    ///
1604 1603
    /// The algorithm computes
1605 1604
    /// - the shortest path to \c t,
1606 1605
    /// - the distance of \c t from the root(s).
1607 1606
    ///
1608 1607
    /// \pre init() must be called and at least one root node should be
1609 1608
    /// added with addSource() before using this function.
1610 1609
    ///
1611 1610
    /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1612 1611
    /// \code
1613 1612
    ///   bool reach = false;
1614 1613
    ///   while ( !b.emptyQueue() && !reach ) {
1615 1614
    ///     b.processNextNode(t, reach);
1616 1615
    ///   }
1617 1616
    /// \endcode
1618 1617
    void start(Node t) {
1619 1618
      bool reach = false;
1620 1619
      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
1621 1620
    }
1622 1621

	
1623 1622
    /// \brief Executes the algorithm until a condition is met.
1624 1623
    ///
1625 1624
    /// Executes the algorithm until a condition is met.
1626 1625
    ///
1627 1626
    /// This method runs the %BFS algorithm from the root node(s) in
1628 1627
    /// order to compute the shortest path to a node \c v with
1629 1628
    /// <tt>nm[v]</tt> true, if such a node can be found.
1630 1629
    ///
1631 1630
    /// \param nm must be a bool (or convertible) node map. The
1632 1631
    /// algorithm will stop when it reaches a node \c v with
1633 1632
    /// <tt>nm[v]</tt> true.
1634 1633
    ///
1635 1634
    /// \return The reached node \c v with <tt>nm[v]</tt> true or
1636 1635
    /// \c INVALID if no such node was found.
1637 1636
    ///
1638 1637
    /// \pre init() must be called and at least one root node should be
1639 1638
    /// added with addSource() before using this function.
1640 1639
    ///
1641 1640
    /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1642 1641
    /// \code
1643 1642
    ///   Node rnode = INVALID;
1644 1643
    ///   while ( !b.emptyQueue() && rnode == INVALID ) {
1645 1644
    ///     b.processNextNode(nm, rnode);
1646 1645
    ///   }
1647 1646
    ///   return rnode;
1648 1647
    /// \endcode
1649 1648
    template <typename NM>
1650 1649
    Node start(const NM &nm) {
1651 1650
      Node rnode = INVALID;
1652 1651
      while ( !emptyQueue() && rnode == INVALID ) {
1653 1652
        processNextNode(nm, rnode);
1654 1653
      }
1655 1654
      return rnode;
1656 1655
    }
1657 1656

	
1658 1657
    /// \brief Runs the algorithm from the given source node.
1659 1658
    ///
1660 1659
    /// This method runs the %BFS algorithm from node \c s
1661 1660
    /// in order to compute the shortest path to each node.
1662 1661
    ///
1663 1662
    /// The algorithm computes
1664 1663
    /// - the shortest path tree,
1665 1664
    /// - the distance of each node from the root.
1666 1665
    ///
1667 1666
    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1668 1667
    ///\code
1669 1668
    ///   b.init();
1670 1669
    ///   b.addSource(s);
1671 1670
    ///   b.start();
1672 1671
    ///\endcode
1673 1672
    void run(Node s) {
1674 1673
      init();
1675 1674
      addSource(s);
1676 1675
      start();
1677 1676
    }
1678 1677

	
1679 1678
    /// \brief Finds the shortest path between \c s and \c t.
1680 1679
    ///
1681 1680
    /// This method runs the %BFS algorithm from node \c s
1682 1681
    /// in order to compute the shortest path to node \c t
1683 1682
    /// (it stops searching when \c t is processed).
1684 1683
    ///
1685 1684
    /// \return \c true if \c t is reachable form \c s.
1686 1685
    ///
1687 1686
    /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1688 1687
    /// shortcut of the following code.
1689 1688
    ///\code
1690 1689
    ///   b.init();
1691 1690
    ///   b.addSource(s);
1692 1691
    ///   b.start(t);
1693 1692
    ///\endcode
1694 1693
    bool run(Node s,Node t) {
1695 1694
      init();
1696 1695
      addSource(s);
1697 1696
      start(t);
1698 1697
      return reached(t);
1699 1698
    }
1700 1699

	
1701 1700
    /// \brief Runs the algorithm to visit all nodes in the digraph.
1702 1701
    ///
1703 1702
    /// This method runs the %BFS algorithm in order to
1704 1703
    /// compute the shortest path to each node.
1705 1704
    ///
1706 1705
    /// The algorithm computes
1707 1706
    /// - the shortest path tree (forest),
1708 1707
    /// - the distance of each node from the root(s).
1709 1708
    ///
1710 1709
    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1711 1710
    ///\code
1712 1711
    ///  b.init();
1713 1712
    ///  for (NodeIt n(gr); n != INVALID; ++n) {
1714 1713
    ///    if (!b.reached(n)) {
1715 1714
    ///      b.addSource(n);
1716 1715
    ///      b.start();
1717 1716
    ///    }
1718 1717
    ///  }
1719 1718
    ///\endcode
1720 1719
    void run() {
1721 1720
      init();
1722 1721
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1723 1722
        if (!reached(it)) {
1724 1723
          addSource(it);
1725 1724
          start();
1726 1725
        }
1727 1726
      }
1728 1727
    }
1729 1728

	
1730 1729
    ///@}
1731 1730

	
1732 1731
    /// \name Query Functions
1733 1732
    /// The result of the %BFS algorithm can be obtained using these
1734 1733
    /// functions.\n
1735 1734
    /// Either \ref lemon::BfsVisit::run() "run()" or
1736 1735
    /// \ref lemon::BfsVisit::start() "start()" must be called before
1737 1736
    /// using them.
1738 1737
    ///@{
1739 1738

	
1740 1739
    /// \brief Checks if a node is reachable from the root(s).
1741 1740
    ///
1742 1741
    /// Returns \c true if \c v is reachable from the root(s).
1743 1742
    /// \pre Either \ref run() or \ref start()
1744 1743
    /// must be called before using this function.
1745 1744
    bool reached(Node v) { return (*_reached)[v]; }
1746 1745

	
1747 1746
    ///@}
1748 1747

	
1749 1748
  };
1750 1749

	
1751 1750
} //END OF NAMESPACE LEMON
1752 1751

	
1753 1752
#endif
Show white space 24576 line context
1 1
#!/bin/bash
2 2

	
3 3
YEAR=`date +2003-%Y`
4 4
HGROOT=`hg root`
5 5

	
6 6
# file enumaration modes
7 7

	
8 8
function all_files() {
9 9
    hg status -a -m -c |
10 10
    cut -d ' ' -f 2 | grep -E '(\.(cc|h|dox)$|Makefile\.am$)' |
11 11
    while read file; do echo $HGROOT/$file; done
12 12
}
13 13

	
14 14
function modified_files() {
15 15
    hg status -a -m |
16 16
    cut -d ' ' -f 2 | grep -E  '(\.(cc|h|dox)$|Makefile\.am$)' |
17 17
    while read file; do echo $HGROOT/$file; done
18 18
}
19 19

	
20 20
function changed_files() {
21 21
    {
22 22
        if [ -n "$HG_PARENT1" ]
23 23
        then
24 24
            hg status --rev $HG_PARENT1:$HG_NODE -a -m
25 25
        fi
26 26
        if [ -n "$HG_PARENT2" ]
27 27
        then
28 28
            hg status --rev $HG_PARENT2:$HG_NODE -a -m
29 29
        fi
30 30
    } | cut -d ' ' -f 2 | grep -E '(\.(cc|h|dox)$|Makefile\.am$)' | 
31 31
    sort | uniq |
32 32
    while read file; do echo $HGROOT/$file; done
33 33
}
34 34

	
35 35
function given_files() {
36 36
    for file in $GIVEN_FILES
37 37
    do
38 38
	echo $file
39 39
    done
40 40
}
41 41

	
42 42
# actions
43 43

	
44 44
function update_action() {
45 45
    if ! diff -q $1 $2 >/dev/null
46 46
    then
47 47
	echo -n " [$3 updated]"
48 48
	rm $2
49 49
	mv $1 $2
50 50
	CHANGED=YES
51 51
    fi
52 52
}
53 53

	
54 54
function update_warning() {
55 55
    echo -n " [$2 warning]"
56 56
    WARNED=YES
57 57
}
58 58

	
59 59
function update_init() {
60 60
    echo Update source files...
61 61
    TOTAL_FILES=0
62 62
    CHANGED_FILES=0
63 63
    WARNED_FILES=0
64 64
}
65 65

	
66 66
function update_done() {
67 67
    echo $CHANGED_FILES out of $TOTAL_FILES files has been changed.
68 68
    echo $WARNED_FILES out of $TOTAL_FILES files triggered warnings.
69 69
}
70 70

	
71 71
function update_begin() {
72 72
    ((TOTAL_FILES++))
73 73
    CHANGED=NO
74 74
    WARNED=NO
75 75
}
76 76

	
77 77
function update_end() {
78 78
    if [ $CHANGED == YES ]
79 79
    then
80 80
	((++CHANGED_FILES))
81 81
    fi
82 82
    if [ $WARNED == YES ]
83 83
    then
84 84
	((++WARNED_FILES))
85 85
    fi
86 86
}
87 87

	
88 88
function check_action() {
89 89
    if ! diff -q $1 $2 >/dev/null
90 90
    then
91
	echo -n " [$3 failed]"
91
	echo
92
	echo -n "      $3 failed at line(s): "
93
	echo -n $(diff $1 $2 | grep '^[0-9]' | sed "s/^\(.*\)c.*$/ \1/g" | 
94
	          sed "s/,/-/g" | paste -s -d',')
92 95
	FAILED=YES
93 96
    fi
94 97
}
95 98

	
96 99
function check_warning() {
97
    echo -n " [$2 warning]"
100
    echo
101
    if [ "$2" == 'long lines' ]
102
    then
103
        echo -n "      $2 warning at line(s): "
104
        echo -n $(grep -n -E '.{81,}' $1 | sed "s/^\([0-9]*\)/ \1\t/g" | 
105
                  cut -f 1 | paste -s -d',')
106
    else
107
        echo -n "      $2 warning"
108
    fi
98 109
    WARNED=YES
99 110
}
100 111

	
101 112
function check_init() {
102 113
    echo Check source files...
103 114
    FAILED_FILES=0
104 115
    WARNED_FILES=0
105 116
    TOTAL_FILES=0
106 117
}
107 118

	
108 119
function check_done() {
109 120
    echo $FAILED_FILES out of $TOTAL_FILES files has been failed.
110 121
    echo $WARNED_FILES out of $TOTAL_FILES files triggered warnings.
111 122

	
112 123
    if [ $FAILED_FILES -gt 0 ]
113 124
    then
114 125
	return 1
115 126
    elif [ $WARNED_FILES -gt 0 ]
116 127
    then
117 128
	if [ "$WARNING" == 'INTERACTIVE' ]
118 129
	then
119 130
	    echo -n "Are the files with warnings acceptable? (yes/no) "
120 131
	    while read answer
121 132
	    do
122 133
		if [ "$answer" == 'yes' ]
123 134
		then
124 135
		    return 0
125 136
		elif [ "$answer" == 'no' ]
126 137
		then
127 138
		    return 1
128 139
		fi
129 140
		echo -n "Are the files with warnings acceptable? (yes/no) "
130 141
	    done
131 142
	elif [ "$WARNING" == 'WERROR' ]
132 143
	then
133 144
	    return 1
134 145
	fi
135 146
    fi
136 147
}
137 148

	
138 149
function check_begin() {
139 150
    ((TOTAL_FILES++))
140 151
    FAILED=NO
141 152
    WARNED=NO
142 153
}
143 154

	
144 155
function check_end() {
145 156
    if [ $FAILED == YES ]
146 157
    then
147 158
	((++FAILED_FILES))
148 159
    fi
149 160
    if [ $WARNED == YES ]
150 161
    then
151 162
	((++WARNED_FILES))
152 163
    fi
153 164
}
154 165

	
155 166

	
156 167

	
157 168
# checks
158 169

	
159 170
function header_check() {
160 171
    if echo $1 | grep -q -E 'Makefile\.am$'
161 172
    then
162 173
	return
163 174
    fi
164 175

	
165 176
    TMP_FILE=`mktemp`
166 177

	
167 178
    (echo "/* -*- mode: C++; indent-tabs-mode: nil; -*-
168 179
 *
169 180
 * This file is a part of LEMON, a generic C++ optimization library.
170 181
 *
171 182
 * Copyright (C) "$YEAR"
172 183
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
173 184
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
174 185
 *
175 186
 * Permission to use, modify and distribute this software is granted
176 187
 * provided that this copyright notice appears in all copies. For
177 188
 * precise terms see the accompanying LICENSE file.
178 189
 *
179 190
 * This software is provided \"AS IS\" with no warranty of any kind,
180 191
 * express or implied, and with no claim as to its suitability for any
181 192
 * purpose.
182 193
 *
183 194
 */
184 195
"
185 196
    awk 'BEGIN { pm=0; }
186 197
     pm==3 { print }
187 198
     /\/\* / && pm==0 { pm=1;}
188 199
     /[^:blank:]/ && (pm==0 || pm==2) { pm=3; print;}
189 200
     /\*\// && pm==1 { pm=2;}
190 201
    ' $1
191 202
    ) >$TMP_FILE
192 203

	
193 204
    "$ACTION"_action "$TMP_FILE" "$1" header
194 205
}
195 206

	
196 207
function tabs_check() {
197 208
    if echo $1 | grep -q -v -E 'Makefile\.am$'
198 209
    then
199 210
        OLD_PATTERN=$(echo -e '\t')
200 211
        NEW_PATTERN='        '
201 212
    else
202 213
        OLD_PATTERN='        '
203 214
        NEW_PATTERN=$(echo -e '\t')
204 215
    fi
205 216
    TMP_FILE=`mktemp`
206 217
    cat $1 | sed -e "s/$OLD_PATTERN/$NEW_PATTERN/g" >$TMP_FILE
207 218

	
208 219
    "$ACTION"_action "$TMP_FILE" "$1" 'tabs'
209 220
}
210 221

	
211 222
function spaces_check() {
212 223
    TMP_FILE=`mktemp`
213 224
    cat $1 | sed -e 's/ \+$//g' >$TMP_FILE
214 225

	
215
    "$ACTION"_action "$TMP_FILE" "$1" 'spaces'
226
    "$ACTION"_action "$TMP_FILE" "$1" 'trailing spaces'
216 227
}
217 228

	
218 229
function long_lines_check() {
219 230
    if cat $1 | grep -q -E '.{81,}'
220 231
    then
221 232
	"$ACTION"_warning $1 'long lines'
222 233
    fi
223 234
}
224 235

	
225 236
# process the file
226 237

	
227 238
function process_file() {
228
    echo -n "    $ACTION " $1...
239
    echo -n "    $ACTION $1..."
229 240

	
230 241
    CHECKING="header tabs spaces long_lines"
231 242

	
232 243
    "$ACTION"_begin $1
233 244
    for check in $CHECKING
234 245
    do
235 246
	"$check"_check $1
236 247
    done
237 248
    "$ACTION"_end $1
238 249
    echo
239 250
}
240 251

	
241 252
function process_all {
242 253
    "$ACTION"_init
243 254
    while read file
244 255
    do
245 256
	process_file $file
246 257
    done < <($FILES)
247 258
    "$ACTION"_done
248 259
}
249 260

	
250 261
while [ $# -gt 0 ]
251 262
do
252 263
    
253 264
    if [ "$1" == '--help' ] || [ "$1" == '-h' ]
254 265
    then
255 266
	echo -n \
256 267
"Usage:
257 268
  $0 [OPTIONS] [files]
258 269
Options:
259 270
  --dry-run|-n
260 271
     Check the files, but do not modify them.
261 272
  --interactive|-i
262 273
     If --dry-run is specified and the checker emits warnings,
263 274
     then the user is asked if the warnings should be considered
264 275
     errors.
265 276
  --werror|-w
266 277
     Make all warnings into errors.
267 278
  --all|-a
268
     All files in the repository will be checked.
279
     Check all source files in the repository.
269 280
  --modified|-m
270 281
     Check only the modified (and new) source files. This option is
271 282
     useful to check the modification before making a commit.
272 283
  --changed|-c
273 284
     Check only the changed source files compared to the parent(s) of
274 285
     the current hg node.  This option is useful as hg hook script.
275 286
     To automatically check all your changes before making a commit,
276 287
     add the following section to the appropriate .hg/hgrc file.
277 288

	
278 289
       [hooks]
279 290
       pretxncommit.checksources = scripts/unify-sources.sh -c -n -i
280 291

	
281 292
  --help|-h
282 293
     Print this help message.
283 294
  files
284
     The files to check/unify. If no file names are given, the
285
     modified source will be checked/unified
286

	
295
     The files to check/unify. If no file names are given, the modified
296
     source files will be checked/unified (just like using the
297
     --modified|-m option).
287 298
"
288 299
        exit 0
289 300
    elif [ "$1" == '--dry-run' ] || [ "$1" == '-n' ]
290 301
    then
291
	[ -n "$ACTION" ] && echo "Invalid option $1" >&2 && exit 1
302
	[ -n "$ACTION" ] && echo "Conflicting action options" >&2 && exit 1
292 303
	ACTION=check
293 304
    elif [ "$1" == "--all" ] || [ "$1" == '-a' ]
294 305
    then
295
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
306
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
296 307
	FILES=all_files
297 308
    elif [ "$1" == "--changed" ] || [ "$1" == '-c' ]
298 309
    then
299
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
310
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
300 311
	FILES=changed_files
301 312
    elif [ "$1" == "--modified" ] || [ "$1" == '-m' ]
302 313
    then
303
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
314
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
304 315
	FILES=modified_files
305 316
    elif [ "$1" == "--interactive" ] || [ "$1" == "-i" ]
306 317
    then
307
	[ -n "$WARNING" ] && echo "Invalid option $1" >&2 && exit 1
318
	[ -n "$WARNING" ] && echo "Conflicting warning options" >&2 && exit 1
308 319
	WARNING='INTERACTIVE'
309 320
    elif [ "$1" == "--werror" ] || [ "$1" == "-w" ]
310 321
    then
311
	[ -n "$WARNING" ] && echo "Invalid option $1" >&2 && exit 1
322
	[ -n "$WARNING" ] && echo "Conflicting warning options" >&2 && exit 1
312 323
	WARNING='WERROR'
313
    elif [ $(echo $1 | cut -c 1) == '-' ]
324
    elif [ $(echo x$1 | cut -c 2) == '-' ]
314 325
    then
315 326
	echo "Invalid option $1" >&2 && exit 1
316 327
    else
317 328
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
318 329
	GIVEN_FILES=$@
319 330
	FILES=given_files
320 331
	break
321 332
    fi
322 333
    
323 334
    shift
324 335
done
325 336

	
326 337
if [ -z $FILES ]
327 338
then
328 339
    FILES=modified_files
329 340
fi
330 341

	
331 342
if [ -z $ACTION ]
332 343
then
333 344
    ACTION=update
334 345
fi
335 346

	
336 347
process_all
0 comments (0 inline)