gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Rename Def* to Set* in Bfs, Dfs, Dijkstra (ticket #134) - DefXyzMap --> SetXyzMap - DefHeap --> SetHeap - DefStandardHeap --> SetStandardHeap - DefOperationTraits --> SetOperationTraits - DefProcessedMapToBeDefaultMap --> SetStandardProcessedMap - Bug fix: SetStandardProcessedMap shouldn't be template
0 4 0
default
4 files changed with 113 insertions and 116 deletions:
↑ Collapse diff ↑
Ignore white space 6 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

	
32 32
namespace lemon {
33 33

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

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

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

	
53 53
    ///This function instantiates a \ref PredMap.
54 54
    ///\param g is the digraph, to which we would like to define the
55 55
    ///\ref PredMap.
56 56
    ///\todo The digraph alone may be insufficient to initialize
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
    ///By default it is a NullMap.
67 67
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
68 68
    ///Instantiates a \ref ProcessedMap.
69 69

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

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

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

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

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

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

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

	
113 113
  ///%BFS algorithm class.
114 114

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

	
141 141
    ///This error represents problems in the initialization of the
142 142
    ///parameters of the algorithm.
143 143
    class UninitializedParameter : public lemon::UninitializedParameter {
144 144
    public:
145 145
      virtual const char* what() const throw() {
146 146
        return "lemon::Bfs::UninitializedParameter";
147 147
      }
148 148
    };
149 149

	
150 150
    ///The type of the digraph the algorithm runs on.
151 151
    typedef typename TR::Digraph Digraph;
152 152

	
153 153
    ///\brief The type of the map that stores the predecessor arcs of the
154 154
    ///shortest paths.
155 155
    typedef typename TR::PredMap PredMap;
156 156
    ///The type of the map that stores the distances of the nodes.
157 157
    typedef typename TR::DistMap DistMap;
158 158
    ///The type of the map that indicates which nodes are reached.
159 159
    typedef typename TR::ReachedMap ReachedMap;
160 160
    ///The type of the map that indicates which nodes are processed.
161 161
    typedef typename TR::ProcessedMap ProcessedMap;
162 162
    ///The type of the paths.
163 163
    typedef PredMapPath<Digraph, PredMap> Path;
164 164

	
165 165
    ///The traits class.
166 166
    typedef TR Traits;
167 167

	
168 168
  private:
169 169

	
170 170
    typedef typename Digraph::Node Node;
171 171
    typedef typename Digraph::NodeIt NodeIt;
172 172
    typedef typename Digraph::Arc Arc;
173 173
    typedef typename Digraph::OutArcIt OutArcIt;
174 174

	
175 175
    //Pointer to the underlying digraph.
176 176
    const Digraph *G;
177 177
    //Pointer to the map of predecessor arcs.
178 178
    PredMap *_pred;
179 179
    //Indicates if _pred is locally allocated (true) or not.
180 180
    bool local_pred;
181 181
    //Pointer to the map of distances.
182 182
    DistMap *_dist;
183 183
    //Indicates if _dist is locally allocated (true) or not.
184 184
    bool local_dist;
185 185
    //Pointer to the map of reached status of the nodes.
186 186
    ReachedMap *_reached;
187 187
    //Indicates if _reached is locally allocated (true) or not.
188 188
    bool local_reached;
189 189
    //Pointer to the map of processed status of the nodes.
190 190
    ProcessedMap *_processed;
191 191
    //Indicates if _processed is locally allocated (true) or not.
192 192
    bool local_processed;
193 193

	
194 194
    std::vector<typename Digraph::Node> _queue;
195 195
    int _queue_head,_queue_tail,_queue_next_dist;
196 196
    int _curr_dist;
197 197

	
198 198
    ///Creates the maps if necessary.
199 199
    ///\todo Better memory allocation (instead of new).
200 200
    void create_maps()
201 201
    {
202 202
      if(!_pred) {
203 203
        local_pred = true;
204 204
        _pred = Traits::createPredMap(*G);
205 205
      }
206 206
      if(!_dist) {
207 207
        local_dist = true;
208 208
        _dist = Traits::createDistMap(*G);
209 209
      }
210 210
      if(!_reached) {
211 211
        local_reached = true;
212 212
        _reached = Traits::createReachedMap(*G);
213 213
      }
214 214
      if(!_processed) {
215 215
        local_processed = true;
216 216
        _processed = Traits::createProcessedMap(*G);
217 217
      }
218 218
    }
219 219

	
220 220
  protected:
221 221

	
222 222
    Bfs() {}
223 223

	
224 224
  public:
225 225

	
226 226
    typedef Bfs Create;
227 227

	
228 228
    ///\name Named template parameters
229 229

	
230 230
    ///@{
231 231

	
232 232
    template <class T>
233
    struct DefPredMapTraits : public Traits {
233
    struct SetPredMapTraits : public Traits {
234 234
      typedef T PredMap;
235 235
      static PredMap *createPredMap(const Digraph &)
236 236
      {
237 237
        throw UninitializedParameter();
238 238
      }
239 239
    };
240 240
    ///\brief \ref named-templ-param "Named parameter" for setting
241 241
    ///\ref PredMap type.
242 242
    ///
243 243
    ///\ref named-templ-param "Named parameter" for setting
244 244
    ///\ref PredMap type.
245 245
    template <class T>
246
    struct DefPredMap : public Bfs< Digraph, DefPredMapTraits<T> > {
247
      typedef Bfs< Digraph, DefPredMapTraits<T> > Create;
246
    struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
247
      typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
248 248
    };
249 249

	
250 250
    template <class T>
251
    struct DefDistMapTraits : public Traits {
251
    struct SetDistMapTraits : public Traits {
252 252
      typedef T DistMap;
253 253
      static DistMap *createDistMap(const Digraph &)
254 254
      {
255 255
        throw UninitializedParameter();
256 256
      }
257 257
    };
258 258
    ///\brief \ref named-templ-param "Named parameter" for setting
259 259
    ///\ref DistMap type.
260 260
    ///
261 261
    ///\ref named-templ-param "Named parameter" for setting
262 262
    ///\ref DistMap type.
263 263
    template <class T>
264
    struct DefDistMap : public Bfs< Digraph, DefDistMapTraits<T> > {
265
      typedef Bfs< Digraph, DefDistMapTraits<T> > Create;
264
    struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
265
      typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
266 266
    };
267 267

	
268 268
    template <class T>
269
    struct DefReachedMapTraits : public Traits {
269
    struct SetReachedMapTraits : public Traits {
270 270
      typedef T ReachedMap;
271 271
      static ReachedMap *createReachedMap(const Digraph &)
272 272
      {
273 273
        throw UninitializedParameter();
274 274
      }
275 275
    };
276 276
    ///\brief \ref named-templ-param "Named parameter" for setting
277 277
    ///\ref ReachedMap type.
278 278
    ///
279 279
    ///\ref named-templ-param "Named parameter" for setting
280 280
    ///\ref ReachedMap type.
281 281
    template <class T>
282
    struct DefReachedMap : public Bfs< Digraph, DefReachedMapTraits<T> > {
283
      typedef Bfs< Digraph, DefReachedMapTraits<T> > Create;
282
    struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
283
      typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
284 284
    };
285 285

	
286 286
    template <class T>
287
    struct DefProcessedMapTraits : public Traits {
287
    struct SetProcessedMapTraits : public Traits {
288 288
      typedef T ProcessedMap;
289 289
      static ProcessedMap *createProcessedMap(const Digraph &)
290 290
      {
291 291
        throw UninitializedParameter();
292 292
      }
293 293
    };
294 294
    ///\brief \ref named-templ-param "Named parameter" for setting
295 295
    ///\ref ProcessedMap type.
296 296
    ///
297 297
    ///\ref named-templ-param "Named parameter" for setting
298 298
    ///\ref ProcessedMap type.
299 299
    template <class T>
300
    struct DefProcessedMap : public Bfs< Digraph, DefProcessedMapTraits<T> > {
301
      typedef Bfs< Digraph, DefProcessedMapTraits<T> > Create;
300
    struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > {
301
      typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create;
302 302
    };
303 303

	
304
    struct DefDigraphProcessedMapTraits : public Traits {
304
    struct SetStandardProcessedMapTraits : public Traits {
305 305
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
306 306
      static ProcessedMap *createProcessedMap(const Digraph &g)
307 307
      {
308 308
        return new ProcessedMap(g);
309 309
      }
310 310
    };
311 311
    ///\brief \ref named-templ-param "Named parameter" for setting
312 312
    ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
313 313
    ///
314 314
    ///\ref named-templ-param "Named parameter" for setting
315 315
    ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
316 316
    ///If you don't set it explicitly, it will be automatically allocated.
317
    template <class T>
318
    struct DefProcessedMapToBeDefaultMap :
319
      public Bfs< Digraph, DefDigraphProcessedMapTraits> {
320
      typedef Bfs< Digraph, DefDigraphProcessedMapTraits> Create;
317
    struct SetStandardProcessedMap :
318
      public Bfs< Digraph, SetStandardProcessedMapTraits > {
319
      typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create;
321 320
    };
322 321

	
323 322
    ///@}
324 323

	
325 324
  public:
326 325

	
327 326
    ///Constructor.
328 327

	
329 328
    ///Constructor.
330 329
    ///\param g The digraph the algorithm runs on.
331 330
    Bfs(const Digraph &g) :
332 331
      G(&g),
333 332
      _pred(NULL), local_pred(false),
334 333
      _dist(NULL), local_dist(false),
335 334
      _reached(NULL), local_reached(false),
336 335
      _processed(NULL), local_processed(false)
337 336
    { }
338 337

	
339 338
    ///Destructor.
340 339
    ~Bfs()
341 340
    {
342 341
      if(local_pred) delete _pred;
343 342
      if(local_dist) delete _dist;
344 343
      if(local_reached) delete _reached;
345 344
      if(local_processed) delete _processed;
346 345
    }
347 346

	
348 347
    ///Sets the map that stores the predecessor arcs.
349 348

	
350 349
    ///Sets the map that stores the predecessor arcs.
351 350
    ///If you don't use this function before calling \ref run(),
352 351
    ///it will allocate one. The destructor deallocates this
353 352
    ///automatically allocated map, of course.
354 353
    ///\return <tt> (*this) </tt>
355 354
    Bfs &predMap(PredMap &m)
356 355
    {
357 356
      if(local_pred) {
358 357
        delete _pred;
359 358
        local_pred=false;
360 359
      }
361 360
      _pred = &m;
362 361
      return *this;
363 362
    }
364 363

	
365 364
    ///Sets the map that indicates which nodes are reached.
366 365

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

	
382 381
    ///Sets the map that indicates which nodes are processed.
383 382

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

	
399 398
    ///Sets the map that stores the distances of the nodes.
400 399

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

	
417 416
  public:
418 417

	
419 418
    ///\name Execution control
420 419
    ///The simplest way to execute the algorithm is to use
421 420
    ///one of the member functions called \ref lemon::Bfs::run() "run()".
422 421
    ///\n
423 422
    ///If you need more control on the execution, first you must call
424 423
    ///\ref lemon::Bfs::init() "init()", then you can add several source
425 424
    ///nodes with \ref lemon::Bfs::addSource() "addSource()".
426 425
    ///Finally \ref lemon::Bfs::start() "start()" will perform the
427 426
    ///actual path computation.
428 427

	
429 428
    ///@{
430 429

	
431 430
    ///Initializes the internal data structures.
432 431

	
433 432
    ///Initializes the internal data structures.
434 433
    ///
435 434
    void init()
436 435
    {
437 436
      create_maps();
438 437
      _queue.resize(countNodes(*G));
439 438
      _queue_head=_queue_tail=0;
440 439
      _curr_dist=1;
441 440
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
442 441
        _pred->set(u,INVALID);
443 442
        _reached->set(u,false);
444 443
        _processed->set(u,false);
445 444
      }
446 445
    }
447 446

	
448 447
    ///Adds a new source node.
449 448

	
450 449
    ///Adds a new source node to the set of nodes to be processed.
451 450
    ///
452 451
    void addSource(Node s)
453 452
    {
454 453
      if(!(*_reached)[s])
455 454
        {
456 455
          _reached->set(s,true);
457 456
          _pred->set(s,INVALID);
458 457
          _dist->set(s,0);
459 458
          _queue[_queue_head++]=s;
460 459
          _queue_next_dist=_queue_head;
461 460
        }
462 461
    }
463 462

	
464 463
    ///Processes the next node.
465 464

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

	
490 489
    ///Processes the next node.
491 490

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

	
523 522
    ///Processes the next node.
524 523

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

	
559 558
    ///The next node to be processed.
560 559

	
561 560
    ///Returns the next node to be processed or \c INVALID if the queue
562 561
    ///is empty.
563 562
    Node nextNode() const
564 563
    {
565 564
      return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
566 565
    }
567 566

	
568 567
    ///\brief Returns \c false if there are nodes
569 568
    ///to be processed.
570 569
    ///
571 570
    ///Returns \c false if there are nodes
572 571
    ///to be processed in the queue.
573 572
    bool emptyQueue() const { return _queue_tail==_queue_head; }
574 573

	
575 574
    ///Returns the number of the nodes to be processed.
576 575

	
577 576
    ///Returns the number of the nodes to be processed in the queue.
578 577
    int queueSize() const { return _queue_head-_queue_tail; }
579 578

	
580 579
    ///Executes the algorithm.
581 580

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

	
605 604
    ///Executes the algorithm until the given target node is reached.
606 605

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

	
632 631
    ///Executes the algorithm until a condition is met.
633 632

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

	
667 666
    ///Runs the algorithm from the given node.
668 667

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

	
688 687
    ///Finds the shortest path between \c s and \c t.
689 688

	
690 689
    ///This method runs the %BFS algorithm from node \c s
691 690
    ///in order to compute the shortest path to \c t.
692 691
    ///
693 692
    ///\return The length of the shortest <tt>s</tt>--<tt>t</tt> path,
694 693
    ///if \c t is reachable form \c s, \c 0 otherwise.
695 694
    ///
696 695
    ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
697 696
    ///shortcut of the following code.
698 697
    ///\code
699 698
    ///  b.init();
700 699
    ///  b.addSource(s);
701 700
    ///  b.start(t);
702 701
    ///\endcode
703 702
    int run(Node s,Node t) {
704 703
      init();
705 704
      addSource(s);
706 705
      start(t);
707 706
      return reached(t) ? _curr_dist : 0;
708 707
    }
709 708

	
710 709
    ///Runs the algorithm to visit all nodes in the digraph.
711 710

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

	
739 738
    ///@}
740 739

	
741 740
    ///\name Query Functions
742 741
    ///The result of the %BFS algorithm can be obtained using these
743 742
    ///functions.\n
744 743
    ///Either \ref lemon::Bfs::run() "run()" or \ref lemon::Bfs::start()
745 744
    ///"start()" must be called before using them.
746 745

	
747 746
    ///@{
748 747

	
749 748
    ///The shortest path to a node.
750 749

	
751 750
    ///Returns the shortest path to a node.
752 751
    ///
753 752
    ///\warning \c t should be reachable from the root(s).
754 753
    ///
755 754
    ///\pre Either \ref run() or \ref start() must be called before
756 755
    ///using this function.
757 756
    Path path(Node t) const { return Path(*G, *_pred, t); }
758 757

	
759 758
    ///The distance of a node from the root(s).
760 759

	
761 760
    ///Returns the distance of a node from the root(s).
762 761
    ///
763 762
    ///\warning If node \c v is not reachable from the root(s), then
764 763
    ///the return value of this function is undefined.
765 764
    ///
766 765
    ///\pre Either \ref run() or \ref start() must be called before
767 766
    ///using this function.
768 767
    int dist(Node v) const { return (*_dist)[v]; }
769 768

	
770 769
    ///Returns the 'previous arc' of the shortest path tree for a node.
771 770

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

	
784 783
    ///Returns the 'previous node' of the shortest path tree for a node.
785 784

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

	
799 798
    ///\brief Returns a const reference to the node map that stores the
800 799
    /// distances of the nodes.
801 800
    ///
802 801
    ///Returns a const reference to the node map that stores the distances
803 802
    ///of the nodes calculated by the algorithm.
804 803
    ///
805 804
    ///\pre Either \ref run() or \ref init()
806 805
    ///must be called before using this function.
807 806
    const DistMap &distMap() const { return *_dist;}
808 807

	
809 808
    ///\brief Returns a const reference to the node map that stores the
810 809
    ///predecessor arcs.
811 810
    ///
812 811
    ///Returns a const reference to the node map that stores the predecessor
813 812
    ///arcs, which form the shortest path tree.
814 813
    ///
815 814
    ///\pre Either \ref run() or \ref init()
816 815
    ///must be called before using this function.
817 816
    const PredMap &predMap() const { return *_pred;}
818 817

	
819 818
    ///Checks if a node is reachable from the root(s).
820 819

	
821 820
    ///Returns \c true if \c v is reachable from the root(s).
822 821
    ///\pre Either \ref run() or \ref start()
823 822
    ///must be called before using this function.
824 823
    bool reached(Node v) const { return (*_reached)[v]; }
825 824

	
826 825
    ///@}
827 826
  };
828 827

	
829 828
  ///Default traits class of bfs() function.
830 829

	
831 830
  ///Default traits class of bfs() function.
832 831
  ///\tparam GR Digraph type.
833 832
  template<class GR>
834 833
  struct BfsWizardDefaultTraits
835 834
  {
836 835
    ///The type of the digraph the algorithm runs on.
837 836
    typedef GR Digraph;
838 837

	
839 838
    ///\brief The type of the map that stores the predecessor
840 839
    ///arcs of the shortest paths.
841 840
    ///
842 841
    ///The type of the map that stores the predecessor
843 842
    ///arcs of the shortest paths.
844 843
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
845 844
    typedef NullMap<typename Digraph::Node,typename Digraph::Arc> PredMap;
846 845
    ///Instantiates a \ref PredMap.
847 846

	
848 847
    ///This function instantiates a \ref PredMap.
849 848
    ///\param g is the digraph, to which we would like to define the
850 849
    ///\ref PredMap.
851 850
    ///\todo The digraph alone may be insufficient to initialize
852 851
#ifdef DOXYGEN
853 852
    static PredMap *createPredMap(const Digraph &g)
854 853
#else
855 854
    static PredMap *createPredMap(const Digraph &)
856 855
#endif
857 856
    {
858 857
      return new PredMap();
859 858
    }
860 859

	
861 860
    ///The type of the map that indicates which nodes are processed.
862 861

	
863 862
    ///The type of the map that indicates which nodes are processed.
864 863
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
865 864
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
866 865
    ///Instantiates a \ref ProcessedMap.
867 866

	
868 867
    ///This function instantiates a \ref ProcessedMap.
869 868
    ///\param g is the digraph, to which
870 869
    ///we would like to define the \ref ProcessedMap.
871 870
#ifdef DOXYGEN
872 871
    static ProcessedMap *createProcessedMap(const Digraph &g)
873 872
#else
874 873
    static ProcessedMap *createProcessedMap(const Digraph &)
875 874
#endif
876 875
    {
877 876
      return new ProcessedMap();
878 877
    }
879 878

	
880 879
    ///The type of the map that indicates which nodes are reached.
881 880

	
882 881
    ///The type of the map that indicates which nodes are reached.
883 882
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
884 883
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
885 884
    ///Instantiates a \ref ReachedMap.
886 885

	
887 886
    ///This function instantiates a \ref ReachedMap.
888 887
    ///\param g is the digraph, to which
889 888
    ///we would like to define the \ref ReachedMap.
890 889
    static ReachedMap *createReachedMap(const Digraph &g)
891 890
    {
892 891
      return new ReachedMap(g);
893 892
    }
894 893

	
895 894
    ///The type of the map that stores the distances of the nodes.
896 895

	
897 896
    ///The type of the map that stores the distances of the nodes.
898 897
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
899 898
    ///
900 899
    typedef NullMap<typename Digraph::Node,int> DistMap;
901 900
    ///Instantiates a \ref DistMap.
902 901

	
903 902
    ///This function instantiates a \ref DistMap.
904 903
    ///\param g is the digraph, to which we would like to define
905 904
    ///the \ref DistMap
906 905
#ifdef DOXYGEN
907 906
    static DistMap *createDistMap(const Digraph &g)
908 907
#else
909 908
    static DistMap *createDistMap(const Digraph &)
910 909
#endif
911 910
    {
912 911
      return new DistMap();
913 912
    }
914 913
  };
915 914

	
916 915
  /// Default traits class used by \ref BfsWizard
917 916

	
918 917
  /// To make it easier to use Bfs algorithm
919 918
  /// we have created a wizard class.
920 919
  /// This \ref BfsWizard class needs default traits,
921 920
  /// as well as the \ref Bfs class.
922 921
  /// The \ref BfsWizardBase is a class to be the default traits of the
923 922
  /// \ref BfsWizard class.
924 923
  template<class GR>
925 924
  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
926 925
  {
927 926

	
928 927
    typedef BfsWizardDefaultTraits<GR> Base;
929 928
  protected:
930 929
    //The type of the nodes in the digraph.
931 930
    typedef typename Base::Digraph::Node Node;
932 931

	
933 932
    //Pointer to the digraph the algorithm runs on.
934 933
    void *_g;
935 934
    //Pointer to the map of reached nodes.
936 935
    void *_reached;
937 936
    //Pointer to the map of processed nodes.
938 937
    void *_processed;
939 938
    //Pointer to the map of predecessors arcs.
940 939
    void *_pred;
941 940
    //Pointer to the map of distances.
942 941
    void *_dist;
943 942
    //Pointer to the source node.
944 943
    Node _source;
945 944

	
946 945
    public:
947 946
    /// Constructor.
948 947

	
949 948
    /// This constructor does not require parameters, therefore it initiates
950 949
    /// all of the attributes to default values (0, INVALID).
951 950
    BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
952 951
                      _dist(0), _source(INVALID) {}
953 952

	
954 953
    /// Constructor.
955 954

	
956 955
    /// This constructor requires some parameters,
957 956
    /// listed in the parameters list.
958 957
    /// Others are initiated to 0.
959 958
    /// \param g The digraph the algorithm runs on.
960 959
    /// \param s The source node.
961 960
    BfsWizardBase(const GR &g, Node s=INVALID) :
962 961
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
963 962
      _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
964 963

	
965 964
  };
966 965

	
967 966
  /// Auxiliary class for the function type interface of BFS algorithm.
968 967

	
969 968
  /// This auxiliary class is created to implement the function type
970 969
  /// interface of \ref Bfs algorithm. It uses the functions and features
971 970
  /// of the plain \ref Bfs, but it is much simpler to use it.
972 971
  /// It should only be used through the \ref bfs() function, which makes
973 972
  /// it easier to use the algorithm.
974 973
  ///
975 974
  /// Simplicity means that the way to change the types defined
976 975
  /// in the traits class is based on functions that returns the new class
977 976
  /// and not on templatable built-in classes.
978 977
  /// When using the plain \ref Bfs
979 978
  /// the new class with the modified type comes from
980 979
  /// the original class by using the ::
981 980
  /// operator. In the case of \ref BfsWizard only
982 981
  /// a function have to be called, and it will
983 982
  /// return the needed class.
984 983
  ///
985 984
  /// It does not have own \ref run() method. When its \ref run() method
986 985
  /// is called, it initiates a plain \ref Bfs object, and calls the
987 986
  /// \ref Bfs::run() method of it.
988 987
  template<class TR>
989 988
  class BfsWizard : public TR
990 989
  {
991 990
    typedef TR Base;
992 991

	
993 992
    ///The type of the digraph the algorithm runs on.
994 993
    typedef typename TR::Digraph Digraph;
995 994

	
996 995
    typedef typename Digraph::Node Node;
997 996
    typedef typename Digraph::NodeIt NodeIt;
998 997
    typedef typename Digraph::Arc Arc;
999 998
    typedef typename Digraph::OutArcIt OutArcIt;
1000 999

	
1001 1000
    ///\brief The type of the map that stores the predecessor
1002 1001
    ///arcs of the shortest paths.
1003 1002
    typedef typename TR::PredMap PredMap;
1004 1003
    ///\brief The type of the map that stores the distances of the nodes.
1005 1004
    typedef typename TR::DistMap DistMap;
1006 1005
    ///\brief The type of the map that indicates which nodes are reached.
1007 1006
    typedef typename TR::ReachedMap ReachedMap;
1008 1007
    ///\brief The type of the map that indicates which nodes are processed.
1009 1008
    typedef typename TR::ProcessedMap ProcessedMap;
1010 1009

	
1011 1010
  public:
1012 1011

	
1013 1012
    /// Constructor.
1014 1013
    BfsWizard() : TR() {}
1015 1014

	
1016 1015
    /// Constructor that requires parameters.
1017 1016

	
1018 1017
    /// Constructor that requires parameters.
1019 1018
    /// These parameters will be the default values for the traits class.
1020 1019
    BfsWizard(const Digraph &g, Node s=INVALID) :
1021 1020
      TR(g,s) {}
1022 1021

	
1023 1022
    ///Copy constructor
1024 1023
    BfsWizard(const TR &b) : TR(b) {}
1025 1024

	
1026 1025
    ~BfsWizard() {}
1027 1026

	
1028 1027
    ///Runs BFS algorithm from a source node.
1029 1028

	
1030 1029
    ///Runs BFS algorithm from a source node.
1031 1030
    ///The node can be given with the \ref source() function.
1032 1031
    void run()
1033 1032
    {
1034 1033
      if(Base::_source==INVALID) throw UninitializedParameter();
1035 1034
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1036 1035
      if(Base::_reached)
1037 1036
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1038 1037
      if(Base::_processed)
1039 1038
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1040 1039
      if(Base::_pred)
1041 1040
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1042 1041
      if(Base::_dist)
1043 1042
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1044 1043
      alg.run(Base::_source);
1045 1044
    }
1046 1045

	
1047 1046
    ///Runs BFS algorithm from the given node.
1048 1047

	
1049 1048
    ///Runs BFS algorithm from the given node.
1050 1049
    ///\param s is the given source.
1051 1050
    void run(Node s)
1052 1051
    {
1053 1052
      Base::_source=s;
1054 1053
      run();
1055 1054
    }
1056 1055

	
1057 1056
    /// Sets the source node, from which the Bfs algorithm runs.
1058 1057

	
1059 1058
    /// Sets the source node, from which the Bfs algorithm runs.
1060 1059
    /// \param s is the source node.
1061 1060
    BfsWizard<TR> &source(Node s)
1062 1061
    {
1063 1062
      Base::_source=s;
1064 1063
      return *this;
1065 1064
    }
1066 1065

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

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

	
1103 1102
    template<class T>
1104
    struct DefProcessedMapBase : public Base {
1103
    struct SetProcessedMapBase : public Base {
1105 1104
      typedef T ProcessedMap;
1106 1105
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1107
      DefProcessedMapBase(const TR &b) : TR(b) {}
1106
      SetProcessedMapBase(const TR &b) : TR(b) {}
1108 1107
    };
1109 1108
    ///\brief \ref named-templ-param "Named parameter"
1110 1109
    ///for setting \ref ProcessedMap object.
1111 1110
    ///
1112 1111
    /// \ref named-templ-param "Named parameter"
1113 1112
    ///for setting \ref ProcessedMap object.
1114 1113
    template<class T>
1115
    BfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1114
    BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1116 1115
    {
1117 1116
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1118
      return BfsWizard<DefProcessedMapBase<T> >(*this);
1117
      return BfsWizard<SetProcessedMapBase<T> >(*this);
1119 1118
    }
1120 1119

	
1121 1120
    template<class T>
1122
    struct DefDistMapBase : public Base {
1121
    struct SetDistMapBase : public Base {
1123 1122
      typedef T DistMap;
1124 1123
      static DistMap *createDistMap(const Digraph &) { return 0; };
1125
      DefDistMapBase(const TR &b) : TR(b) {}
1124
      SetDistMapBase(const TR &b) : TR(b) {}
1126 1125
    };
1127 1126
    ///\brief \ref named-templ-param "Named parameter"
1128 1127
    ///for setting \ref DistMap object.
1129 1128
    ///
1130 1129
    /// \ref named-templ-param "Named parameter"
1131 1130
    ///for setting \ref DistMap object.
1132 1131
    template<class T>
1133
    BfsWizard<DefDistMapBase<T> > distMap(const T &t)
1132
    BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1134 1133
    {
1135 1134
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1136
      return BfsWizard<DefDistMapBase<T> >(*this);
1135
      return BfsWizard<SetDistMapBase<T> >(*this);
1137 1136
    }
1138 1137

	
1139 1138
  };
1140 1139

	
1141 1140
  ///Function type interface for Bfs algorithm.
1142 1141

	
1143 1142
  /// \ingroup search
1144 1143
  ///Function type interface for Bfs algorithm.
1145 1144
  ///
1146 1145
  ///This function also has several
1147 1146
  ///\ref named-templ-func-param "named parameters",
1148 1147
  ///they are declared as the members of class \ref BfsWizard.
1149 1148
  ///The following
1150 1149
  ///example shows how to use these parameters.
1151 1150
  ///\code
1152 1151
  ///  bfs(g,source).predMap(preds).run();
1153 1152
  ///\endcode
1154 1153
  ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1155 1154
  ///to the end of the parameter list.
1156 1155
  ///\sa BfsWizard
1157 1156
  ///\sa Bfs
1158 1157
  template<class GR>
1159 1158
  BfsWizard<BfsWizardBase<GR> >
1160 1159
  bfs(const GR &g,typename GR::Node s=INVALID)
1161 1160
  {
1162 1161
    return BfsWizard<BfsWizardBase<GR> >(g,s);
1163 1162
  }
1164 1163

	
1165 1164
#ifdef DOXYGEN
1166 1165
  /// \brief Visitor class for BFS.
1167 1166
  ///
1168 1167
  /// This class defines the interface of the BfsVisit events, and
1169 1168
  /// it could be the base of a real visitor class.
1170 1169
  template <typename _Digraph>
1171 1170
  struct BfsVisitor {
1172 1171
    typedef _Digraph Digraph;
1173 1172
    typedef typename Digraph::Arc Arc;
1174 1173
    typedef typename Digraph::Node Node;
1175 1174
    /// \brief Called for the source node(s) of the BFS.
1176 1175
    ///
1177 1176
    /// This function is called for the source node(s) of the BFS.
1178 1177
    void start(const Node& node) {}
1179 1178
    /// \brief Called when a node is reached first time.
1180 1179
    ///
1181 1180
    /// This function is called when a node is reached first time.
1182 1181
    void reach(const Node& node) {}
1183 1182
    /// \brief Called when a node is processed.
1184 1183
    ///
1185 1184
    /// This function is called when a node is processed.
1186 1185
    void process(const Node& node) {}
1187 1186
    /// \brief Called when an arc reaches a new node.
1188 1187
    ///
1189 1188
    /// This function is called when the BFS finds an arc whose target node
1190 1189
    /// is not reached yet.
1191 1190
    void discover(const Arc& arc) {}
1192 1191
    /// \brief Called when an arc is examined but its target node is
1193 1192
    /// already discovered.
1194 1193
    ///
1195 1194
    /// This function is called when an arc is examined but its target node is
1196 1195
    /// already discovered.
1197 1196
    void examine(const Arc& arc) {}
1198 1197
  };
1199 1198
#else
1200 1199
  template <typename _Digraph>
1201 1200
  struct BfsVisitor {
1202 1201
    typedef _Digraph Digraph;
1203 1202
    typedef typename Digraph::Arc Arc;
1204 1203
    typedef typename Digraph::Node Node;
1205 1204
    void start(const Node&) {}
1206 1205
    void reach(const Node&) {}
1207 1206
    void process(const Node&) {}
1208 1207
    void discover(const Arc&) {}
1209 1208
    void examine(const Arc&) {}
1210 1209

	
1211 1210
    template <typename _Visitor>
1212 1211
    struct Constraints {
1213 1212
      void constraints() {
1214 1213
        Arc arc;
1215 1214
        Node node;
1216 1215
        visitor.start(node);
1217 1216
        visitor.reach(node);
1218 1217
        visitor.process(node);
1219 1218
        visitor.discover(arc);
1220 1219
        visitor.examine(arc);
1221 1220
      }
1222 1221
      _Visitor& visitor;
1223 1222
    };
1224 1223
  };
1225 1224
#endif
1226 1225

	
1227 1226
  /// \brief Default traits class of BfsVisit class.
1228 1227
  ///
1229 1228
  /// Default traits class of BfsVisit class.
1230 1229
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1231 1230
  template<class _Digraph>
1232 1231
  struct BfsVisitDefaultTraits {
1233 1232

	
1234 1233
    /// \brief The type of the digraph the algorithm runs on.
1235 1234
    typedef _Digraph Digraph;
1236 1235

	
1237 1236
    /// \brief The type of the map that indicates which nodes are reached.
1238 1237
    ///
1239 1238
    /// The type of the map that indicates which nodes are reached.
1240 1239
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1241 1240
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1242 1241

	
1243 1242
    /// \brief Instantiates a \ref ReachedMap.
1244 1243
    ///
1245 1244
    /// This function instantiates a \ref ReachedMap.
1246 1245
    /// \param digraph is the digraph, to which
1247 1246
    /// we would like to define the \ref ReachedMap.
1248 1247
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1249 1248
      return new ReachedMap(digraph);
1250 1249
    }
1251 1250

	
1252 1251
  };
1253 1252

	
1254 1253
  /// \ingroup search
1255 1254
  ///
1256 1255
  /// \brief %BFS algorithm class with visitor interface.
1257 1256
  ///
1258 1257
  /// This class provides an efficient implementation of the %BFS algorithm
1259 1258
  /// with visitor interface.
1260 1259
  ///
1261 1260
  /// The %BfsVisit class provides an alternative interface to the Bfs
1262 1261
  /// class. It works with callback mechanism, the BfsVisit object calls
1263 1262
  /// the member functions of the \c Visitor class on every BFS event.
1264 1263
  ///
1265 1264
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1266 1265
  /// The default value is
1267 1266
  /// \ref ListDigraph. The value of _Digraph is not used directly by
1268 1267
  /// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits.
1269 1268
  /// \tparam _Visitor The Visitor type that is used by the algorithm.
1270 1269
  /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which
1271 1270
  /// does not observe the BFS events. If you want to observe the BFS
1272 1271
  /// events, you should implement your own visitor class.
1273 1272
  /// \tparam _Traits Traits class to set various data types used by the
1274 1273
  /// algorithm. The default traits class is
1275 1274
  /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
1276 1275
  /// See \ref BfsVisitDefaultTraits for the documentation of
1277 1276
  /// a BFS visit traits class.
1278 1277
#ifdef DOXYGEN
1279 1278
  template <typename _Digraph, typename _Visitor, typename _Traits>
1280 1279
#else
1281 1280
  template <typename _Digraph = ListDigraph,
1282 1281
            typename _Visitor = BfsVisitor<_Digraph>,
1283 1282
            typename _Traits = BfsDefaultTraits<_Digraph> >
1284 1283
#endif
1285 1284
  class BfsVisit {
1286 1285
  public:
1287 1286

	
1288 1287
    /// \brief \ref Exception for uninitialized parameters.
1289 1288
    ///
1290 1289
    /// This error represents problems in the initialization
1291 1290
    /// of the parameters of the algorithm.
1292 1291
    class UninitializedParameter : public lemon::UninitializedParameter {
1293 1292
    public:
1294 1293
      virtual const char* what() const throw()
1295 1294
      {
1296 1295
        return "lemon::BfsVisit::UninitializedParameter";
1297 1296
      }
1298 1297
    };
1299 1298

	
1300 1299
    ///The traits class.
1301 1300
    typedef _Traits Traits;
1302 1301

	
1303 1302
    ///The type of the digraph the algorithm runs on.
1304 1303
    typedef typename Traits::Digraph Digraph;
1305 1304

	
1306 1305
    ///The visitor type used by the algorithm.
1307 1306
    typedef _Visitor Visitor;
1308 1307

	
1309 1308
    ///The type of the map that indicates which nodes are reached.
1310 1309
    typedef typename Traits::ReachedMap ReachedMap;
1311 1310

	
1312 1311
  private:
1313 1312

	
1314 1313
    typedef typename Digraph::Node Node;
1315 1314
    typedef typename Digraph::NodeIt NodeIt;
1316 1315
    typedef typename Digraph::Arc Arc;
1317 1316
    typedef typename Digraph::OutArcIt OutArcIt;
1318 1317

	
1319 1318
    //Pointer to the underlying digraph.
1320 1319
    const Digraph *_digraph;
1321 1320
    //Pointer to the visitor object.
1322 1321
    Visitor *_visitor;
1323 1322
    //Pointer to the map of reached status of the nodes.
1324 1323
    ReachedMap *_reached;
1325 1324
    //Indicates if _reached is locally allocated (true) or not.
1326 1325
    bool local_reached;
1327 1326

	
1328 1327
    std::vector<typename Digraph::Node> _list;
1329 1328
    int _list_front, _list_back;
1330 1329

	
1331 1330
    ///Creates the maps if necessary.
1332 1331
    ///\todo Better memory allocation (instead of new).
1333 1332
    void create_maps() {
1334 1333
      if(!_reached) {
1335 1334
        local_reached = true;
1336 1335
        _reached = Traits::createReachedMap(*_digraph);
1337 1336
      }
1338 1337
    }
1339 1338

	
1340 1339
  protected:
1341 1340

	
1342 1341
    BfsVisit() {}
1343 1342

	
1344 1343
  public:
1345 1344

	
1346 1345
    typedef BfsVisit Create;
1347 1346

	
1348 1347
    /// \name Named template parameters
1349 1348

	
1350 1349
    ///@{
1351 1350
    template <class T>
1352
    struct DefReachedMapTraits : public Traits {
1351
    struct SetReachedMapTraits : public Traits {
1353 1352
      typedef T ReachedMap;
1354 1353
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1355 1354
        throw UninitializedParameter();
1356 1355
      }
1357 1356
    };
1358 1357
    /// \brief \ref named-templ-param "Named parameter" for setting
1359 1358
    /// ReachedMap type.
1360 1359
    ///
1361 1360
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1362 1361
    template <class T>
1363
    struct DefReachedMap : public BfsVisit< Digraph, Visitor,
1364
                                            DefReachedMapTraits<T> > {
1365
      typedef BfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create;
1362
    struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1363
                                            SetReachedMapTraits<T> > {
1364
      typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1366 1365
    };
1367 1366
    ///@}
1368 1367

	
1369 1368
  public:
1370 1369

	
1371 1370
    /// \brief Constructor.
1372 1371
    ///
1373 1372
    /// Constructor.
1374 1373
    ///
1375 1374
    /// \param digraph The digraph the algorithm runs on.
1376 1375
    /// \param visitor The visitor object of the algorithm.
1377 1376
    BfsVisit(const Digraph& digraph, Visitor& visitor)
1378 1377
      : _digraph(&digraph), _visitor(&visitor),
1379 1378
        _reached(0), local_reached(false) {}
1380 1379

	
1381 1380
    /// \brief Destructor.
1382 1381
    ~BfsVisit() {
1383 1382
      if(local_reached) delete _reached;
1384 1383
    }
1385 1384

	
1386 1385
    /// \brief Sets the map that indicates which nodes are reached.
1387 1386
    ///
1388 1387
    /// Sets the map that indicates which nodes are reached.
1389 1388
    /// If you don't use this function before calling \ref run(),
1390 1389
    /// it will allocate one. The destructor deallocates this
1391 1390
    /// automatically allocated map, of course.
1392 1391
    /// \return <tt> (*this) </tt>
1393 1392
    BfsVisit &reachedMap(ReachedMap &m) {
1394 1393
      if(local_reached) {
1395 1394
        delete _reached;
1396 1395
        local_reached = false;
1397 1396
      }
1398 1397
      _reached = &m;
1399 1398
      return *this;
1400 1399
    }
1401 1400

	
1402 1401
  public:
1403 1402

	
1404 1403
    /// \name Execution control
1405 1404
    /// The simplest way to execute the algorithm is to use
1406 1405
    /// one of the member functions called \ref lemon::BfsVisit::run()
1407 1406
    /// "run()".
1408 1407
    /// \n
1409 1408
    /// If you need more control on the execution, first you must call
1410 1409
    /// \ref lemon::BfsVisit::init() "init()", then you can add several
1411 1410
    /// source nodes with \ref lemon::BfsVisit::addSource() "addSource()".
1412 1411
    /// Finally \ref lemon::BfsVisit::start() "start()" will perform the
1413 1412
    /// actual path computation.
1414 1413

	
1415 1414
    /// @{
1416 1415

	
1417 1416
    /// \brief Initializes the internal data structures.
1418 1417
    ///
1419 1418
    /// Initializes the internal data structures.
1420 1419
    void init() {
1421 1420
      create_maps();
1422 1421
      _list.resize(countNodes(*_digraph));
1423 1422
      _list_front = _list_back = -1;
1424 1423
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1425 1424
        _reached->set(u, false);
1426 1425
      }
1427 1426
    }
1428 1427

	
1429 1428
    /// \brief Adds a new source node.
1430 1429
    ///
1431 1430
    /// Adds a new source node to the set of nodes to be processed.
1432 1431
    void addSource(Node s) {
1433 1432
      if(!(*_reached)[s]) {
1434 1433
          _reached->set(s,true);
1435 1434
          _visitor->start(s);
1436 1435
          _visitor->reach(s);
1437 1436
          _list[++_list_back] = s;
1438 1437
        }
1439 1438
    }
1440 1439

	
1441 1440
    /// \brief Processes the next node.
1442 1441
    ///
1443 1442
    /// Processes the next node.
1444 1443
    ///
1445 1444
    /// \return The processed node.
1446 1445
    ///
1447 1446
    /// \pre The queue must not be empty.
1448 1447
    Node processNextNode() {
1449 1448
      Node n = _list[++_list_front];
1450 1449
      _visitor->process(n);
1451 1450
      Arc e;
1452 1451
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1453 1452
        Node m = _digraph->target(e);
1454 1453
        if (!(*_reached)[m]) {
1455 1454
          _visitor->discover(e);
1456 1455
          _visitor->reach(m);
1457 1456
          _reached->set(m, true);
1458 1457
          _list[++_list_back] = m;
1459 1458
        } else {
1460 1459
          _visitor->examine(e);
1461 1460
        }
1462 1461
      }
1463 1462
      return n;
1464 1463
    }
1465 1464

	
1466 1465
    /// \brief Processes the next node.
1467 1466
    ///
1468 1467
    /// Processes the next node and checks if the given target node
1469 1468
    /// is reached. If the target node is reachable from the processed
1470 1469
    /// node, then the \c reach parameter will be set to \c true.
1471 1470
    ///
1472 1471
    /// \param target The target node.
1473 1472
    /// \retval reach Indicates if the target node is reached.
1474 1473
    /// It should be initially \c false.
1475 1474
    ///
1476 1475
    /// \return The processed node.
1477 1476
    ///
1478 1477
    /// \pre The queue must not be empty.
1479 1478
    Node processNextNode(Node target, bool& reach) {
1480 1479
      Node n = _list[++_list_front];
1481 1480
      _visitor->process(n);
1482 1481
      Arc e;
1483 1482
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1484 1483
        Node m = _digraph->target(e);
1485 1484
        if (!(*_reached)[m]) {
1486 1485
          _visitor->discover(e);
1487 1486
          _visitor->reach(m);
1488 1487
          _reached->set(m, true);
1489 1488
          _list[++_list_back] = m;
1490 1489
          reach = reach || (target == m);
1491 1490
        } else {
1492 1491
          _visitor->examine(e);
1493 1492
        }
1494 1493
      }
1495 1494
      return n;
1496 1495
    }
1497 1496

	
1498 1497
    /// \brief Processes the next node.
1499 1498
    ///
1500 1499
    /// Processes the next node and checks if at least one of reached
1501 1500
    /// nodes has \c true value in the \c nm node map. If one node
1502 1501
    /// with \c true value is reachable from the processed node, then the
1503 1502
    /// \c rnode parameter will be set to the first of such nodes.
1504 1503
    ///
1505 1504
    /// \param nm A \c bool (or convertible) node map that indicates the
1506 1505
    /// possible targets.
1507 1506
    /// \retval rnode The reached target node.
1508 1507
    /// It should be initially \c INVALID.
1509 1508
    ///
1510 1509
    /// \return The processed node.
1511 1510
    ///
1512 1511
    /// \pre The queue must not be empty.
1513 1512
    template <typename NM>
1514 1513
    Node processNextNode(const NM& nm, Node& rnode) {
1515 1514
      Node n = _list[++_list_front];
1516 1515
      _visitor->process(n);
1517 1516
      Arc e;
1518 1517
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1519 1518
        Node m = _digraph->target(e);
1520 1519
        if (!(*_reached)[m]) {
1521 1520
          _visitor->discover(e);
1522 1521
          _visitor->reach(m);
1523 1522
          _reached->set(m, true);
1524 1523
          _list[++_list_back] = m;
1525 1524
          if (nm[m] && rnode == INVALID) rnode = m;
1526 1525
        } else {
1527 1526
          _visitor->examine(e);
1528 1527
        }
1529 1528
      }
1530 1529
      return n;
1531 1530
    }
1532 1531

	
1533 1532
    /// \brief The next node to be processed.
1534 1533
    ///
1535 1534
    /// Returns the next node to be processed or \c INVALID if the queue
1536 1535
    /// is empty.
1537 1536
    Node nextNode() const {
1538 1537
      return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1539 1538
    }
1540 1539

	
1541 1540
    /// \brief Returns \c false if there are nodes
1542 1541
    /// to be processed.
1543 1542
    ///
1544 1543
    /// Returns \c false if there are nodes
1545 1544
    /// to be processed in the queue.
1546 1545
    bool emptyQueue() const { return _list_front == _list_back; }
1547 1546

	
1548 1547
    /// \brief Returns the number of the nodes to be processed.
1549 1548
    ///
1550 1549
    /// Returns the number of the nodes to be processed in the queue.
1551 1550
    int queueSize() const { return _list_back - _list_front; }
1552 1551

	
1553 1552
    /// \brief Executes the algorithm.
1554 1553
    ///
1555 1554
    /// Executes the algorithm.
1556 1555
    ///
1557 1556
    /// This method runs the %BFS algorithm from the root node(s)
1558 1557
    /// in order to compute the shortest path to each node.
1559 1558
    ///
1560 1559
    /// The algorithm computes
1561 1560
    /// - the shortest path tree (forest),
1562 1561
    /// - the distance of each node from the root(s).
1563 1562
    ///
1564 1563
    /// \pre init() must be called and at least one root node should be added
1565 1564
    /// with addSource() before using this function.
1566 1565
    ///
1567 1566
    /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1568 1567
    /// \code
1569 1568
    ///   while ( !b.emptyQueue() ) {
1570 1569
    ///     b.processNextNode();
1571 1570
    ///   }
1572 1571
    /// \endcode
1573 1572
    void start() {
1574 1573
      while ( !emptyQueue() ) processNextNode();
1575 1574
    }
1576 1575

	
1577 1576
    /// \brief Executes the algorithm until the given target node is reached.
1578 1577
    ///
1579 1578
    /// Executes the algorithm until the given target node is reached.
1580 1579
    ///
1581 1580
    /// This method runs the %BFS algorithm from the root node(s)
1582 1581
    /// in order to compute the shortest path to \c dest.
1583 1582
    ///
1584 1583
    /// The algorithm computes
1585 1584
    /// - the shortest path to \c dest,
1586 1585
    /// - the distance of \c dest from the root(s).
1587 1586
    ///
1588 1587
    /// \pre init() must be called and at least one root node should be
1589 1588
    /// added with addSource() before using this function.
1590 1589
    ///
1591 1590
    /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1592 1591
    /// \code
1593 1592
    ///   bool reach = false;
1594 1593
    ///   while ( !b.emptyQueue() && !reach ) {
1595 1594
    ///     b.processNextNode(t, reach);
1596 1595
    ///   }
1597 1596
    /// \endcode
1598 1597
    void start(Node dest) {
1599 1598
      bool reach = false;
1600 1599
      while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
1601 1600
    }
1602 1601

	
1603 1602
    /// \brief Executes the algorithm until a condition is met.
1604 1603
    ///
1605 1604
    /// Executes the algorithm until a condition is met.
1606 1605
    ///
1607 1606
    /// This method runs the %BFS algorithm from the root node(s) in
1608 1607
    /// order to compute the shortest path to a node \c v with
1609 1608
    /// <tt>nm[v]</tt> true, if such a node can be found.
1610 1609
    ///
1611 1610
    /// \param nm must be a bool (or convertible) node map. The
1612 1611
    /// algorithm will stop when it reaches a node \c v with
1613 1612
    /// <tt>nm[v]</tt> true.
1614 1613
    ///
1615 1614
    /// \return The reached node \c v with <tt>nm[v]</tt> true or
1616 1615
    /// \c INVALID if no such node was found.
1617 1616
    ///
1618 1617
    /// \pre init() must be called and at least one root node should be
1619 1618
    /// added with addSource() before using this function.
1620 1619
    ///
1621 1620
    /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1622 1621
    /// \code
1623 1622
    ///   Node rnode = INVALID;
1624 1623
    ///   while ( !b.emptyQueue() && rnode == INVALID ) {
1625 1624
    ///     b.processNextNode(nm, rnode);
1626 1625
    ///   }
1627 1626
    ///   return rnode;
1628 1627
    /// \endcode
1629 1628
    template <typename NM>
1630 1629
    Node start(const NM &nm) {
1631 1630
      Node rnode = INVALID;
1632 1631
      while ( !emptyQueue() && rnode == INVALID ) {
1633 1632
        processNextNode(nm, rnode);
1634 1633
      }
1635 1634
      return rnode;
1636 1635
    }
1637 1636

	
1638 1637
    /// \brief Runs the algorithm from the given node.
1639 1638
    ///
1640 1639
    /// This method runs the %BFS algorithm from node \c s
1641 1640
    /// in order to compute the shortest path to each node.
1642 1641
    ///
1643 1642
    /// The algorithm computes
1644 1643
    /// - the shortest path tree,
1645 1644
    /// - the distance of each node from the root.
1646 1645
    ///
1647 1646
    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1648 1647
    ///\code
1649 1648
    ///   b.init();
1650 1649
    ///   b.addSource(s);
1651 1650
    ///   b.start();
1652 1651
    ///\endcode
1653 1652
    void run(Node s) {
1654 1653
      init();
1655 1654
      addSource(s);
1656 1655
      start();
1657 1656
    }
1658 1657

	
1659 1658
    /// \brief Runs the algorithm to visit all nodes in the digraph.
1660 1659
    ///
1661 1660
    /// This method runs the %BFS algorithm in order to
1662 1661
    /// compute the shortest path to each node.
1663 1662
    ///
1664 1663
    /// The algorithm computes
1665 1664
    /// - the shortest path tree (forest),
1666 1665
    /// - the distance of each node from the root(s).
1667 1666
    ///
1668 1667
    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1669 1668
    ///\code
1670 1669
    ///  b.init();
1671 1670
    ///  for (NodeIt n(gr); n != INVALID; ++n) {
1672 1671
    ///    if (!b.reached(n)) {
1673 1672
    ///      b.addSource(n);
1674 1673
    ///      b.start();
1675 1674
    ///    }
1676 1675
    ///  }
1677 1676
    ///\endcode
1678 1677
    void run() {
1679 1678
      init();
1680 1679
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1681 1680
        if (!reached(it)) {
1682 1681
          addSource(it);
1683 1682
          start();
1684 1683
        }
1685 1684
      }
1686 1685
    }
1687 1686

	
1688 1687
    ///@}
1689 1688

	
1690 1689
    /// \name Query Functions
1691 1690
    /// The result of the %BFS algorithm can be obtained using these
1692 1691
    /// functions.\n
1693 1692
    /// Either \ref lemon::BfsVisit::run() "run()" or
1694 1693
    /// \ref lemon::BfsVisit::start() "start()" must be called before
1695 1694
    /// using them.
1696 1695
    ///@{
1697 1696

	
1698 1697
    /// \brief Checks if a node is reachable from the root(s).
1699 1698
    ///
1700 1699
    /// Returns \c true if \c v is reachable from the root(s).
1701 1700
    /// \pre Either \ref run() or \ref start()
1702 1701
    /// must be called before using this function.
1703 1702
    bool reached(Node v) { return (*_reached)[v]; }
1704 1703

	
1705 1704
    ///@}
1706 1705

	
1707 1706
  };
1708 1707

	
1709 1708
} //END OF NAMESPACE LEMON
1710 1709

	
1711 1710
#endif
Ignore white space 6 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_DFS_H
20 20
#define LEMON_DFS_H
21 21

	
22 22
///\ingroup search
23 23
///\file
24 24
///\brief DFS 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/assert.h>
31 31
#include <lemon/maps.h>
32 32

	
33 33
namespace lemon {
34 34

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

	
37 37
  ///Default traits class of Dfs class.
38 38
  ///\tparam GR Digraph type.
39 39
  template<class GR>
40 40
  struct DfsDefaultTraits
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 %DFS paths.
47 47
    ///
48 48
    ///The type of the map that stores the predecessor
49 49
    ///arcs of the %DFS 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 \ref PredMap.
53 53

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

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

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

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

	
83 83
    ///The type of the map that indicates which nodes are reached.
84 84

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

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

	
98 98
    ///The type of the map that stores the distances of the nodes.
99 99

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

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

	
114 114
  ///%DFS algorithm class.
115 115

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

	
142 142
    ///This error represents problems in the initialization of the
143 143
    ///parameters of the algorithm.
144 144
    class UninitializedParameter : public lemon::UninitializedParameter {
145 145
    public:
146 146
      virtual const char* what() const throw() {
147 147
        return "lemon::Dfs::UninitializedParameter";
148 148
      }
149 149
    };
150 150

	
151 151
    ///The type of the digraph the algorithm runs on.
152 152
    typedef typename TR::Digraph Digraph;
153 153

	
154 154
    ///\brief The type of the map that stores the predecessor arcs of the
155 155
    ///DFS paths.
156 156
    typedef typename TR::PredMap PredMap;
157 157
    ///The type of the map that stores the distances of the nodes.
158 158
    typedef typename TR::DistMap DistMap;
159 159
    ///The type of the map that indicates which nodes are reached.
160 160
    typedef typename TR::ReachedMap ReachedMap;
161 161
    ///The type of the map that indicates which nodes are processed.
162 162
    typedef typename TR::ProcessedMap ProcessedMap;
163 163
    ///The type of the paths.
164 164
    typedef PredMapPath<Digraph, PredMap> Path;
165 165

	
166 166
    ///The traits class.
167 167
    typedef TR Traits;
168 168

	
169 169
  private:
170 170

	
171 171
    typedef typename Digraph::Node Node;
172 172
    typedef typename Digraph::NodeIt NodeIt;
173 173
    typedef typename Digraph::Arc Arc;
174 174
    typedef typename Digraph::OutArcIt OutArcIt;
175 175

	
176 176
    //Pointer to the underlying digraph.
177 177
    const Digraph *G;
178 178
    //Pointer to the map of predecessor arcs.
179 179
    PredMap *_pred;
180 180
    //Indicates if _pred is locally allocated (true) or not.
181 181
    bool local_pred;
182 182
    //Pointer to the map of distances.
183 183
    DistMap *_dist;
184 184
    //Indicates if _dist is locally allocated (true) or not.
185 185
    bool local_dist;
186 186
    //Pointer to the map of reached status of the nodes.
187 187
    ReachedMap *_reached;
188 188
    //Indicates if _reached is locally allocated (true) or not.
189 189
    bool local_reached;
190 190
    //Pointer to the map of processed status of the nodes.
191 191
    ProcessedMap *_processed;
192 192
    //Indicates if _processed is locally allocated (true) or not.
193 193
    bool local_processed;
194 194

	
195 195
    std::vector<typename Digraph::OutArcIt> _stack;
196 196
    int _stack_head;
197 197

	
198 198
    ///Creates the maps if necessary.
199 199
    ///\todo Better memory allocation (instead of new).
200 200
    void create_maps()
201 201
    {
202 202
      if(!_pred) {
203 203
        local_pred = true;
204 204
        _pred = Traits::createPredMap(*G);
205 205
      }
206 206
      if(!_dist) {
207 207
        local_dist = true;
208 208
        _dist = Traits::createDistMap(*G);
209 209
      }
210 210
      if(!_reached) {
211 211
        local_reached = true;
212 212
        _reached = Traits::createReachedMap(*G);
213 213
      }
214 214
      if(!_processed) {
215 215
        local_processed = true;
216 216
        _processed = Traits::createProcessedMap(*G);
217 217
      }
218 218
    }
219 219

	
220 220
  protected:
221 221

	
222 222
    Dfs() {}
223 223

	
224 224
  public:
225 225

	
226 226
    typedef Dfs Create;
227 227

	
228 228
    ///\name Named template parameters
229 229

	
230 230
    ///@{
231 231

	
232 232
    template <class T>
233
    struct DefPredMapTraits : public Traits {
233
    struct SetPredMapTraits : public Traits {
234 234
      typedef T PredMap;
235 235
      static PredMap *createPredMap(const Digraph &)
236 236
      {
237 237
        throw UninitializedParameter();
238 238
      }
239 239
    };
240 240
    ///\brief \ref named-templ-param "Named parameter" for setting
241 241
    ///\ref PredMap type.
242 242
    ///
243 243
    ///\ref named-templ-param "Named parameter" for setting
244 244
    ///\ref PredMap type.
245 245
    template <class T>
246
    struct DefPredMap : public Dfs<Digraph, DefPredMapTraits<T> > {
247
      typedef Dfs<Digraph, DefPredMapTraits<T> > Create;
246
    struct SetPredMap : public Dfs<Digraph, SetPredMapTraits<T> > {
247
      typedef Dfs<Digraph, SetPredMapTraits<T> > Create;
248 248
    };
249 249

	
250 250
    template <class T>
251
    struct DefDistMapTraits : public Traits {
251
    struct SetDistMapTraits : public Traits {
252 252
      typedef T DistMap;
253 253
      static DistMap *createDistMap(const Digraph &)
254 254
      {
255 255
        throw UninitializedParameter();
256 256
      }
257 257
    };
258 258
    ///\brief \ref named-templ-param "Named parameter" for setting
259 259
    ///\ref DistMap type.
260 260
    ///
261 261
    ///\ref named-templ-param "Named parameter" for setting
262 262
    ///\ref DistMap type.
263 263
    template <class T>
264
    struct DefDistMap : public Dfs< Digraph, DefDistMapTraits<T> > {
265
      typedef Dfs<Digraph, DefDistMapTraits<T> > Create;
264
    struct SetDistMap : public Dfs< Digraph, SetDistMapTraits<T> > {
265
      typedef Dfs<Digraph, SetDistMapTraits<T> > Create;
266 266
    };
267 267

	
268 268
    template <class T>
269
    struct DefReachedMapTraits : public Traits {
269
    struct SetReachedMapTraits : public Traits {
270 270
      typedef T ReachedMap;
271 271
      static ReachedMap *createReachedMap(const Digraph &)
272 272
      {
273 273
        throw UninitializedParameter();
274 274
      }
275 275
    };
276 276
    ///\brief \ref named-templ-param "Named parameter" for setting
277 277
    ///\ref ReachedMap type.
278 278
    ///
279 279
    ///\ref named-templ-param "Named parameter" for setting
280 280
    ///\ref ReachedMap type.
281 281
    template <class T>
282
    struct DefReachedMap : public Dfs< Digraph, DefReachedMapTraits<T> > {
283
      typedef Dfs< Digraph, DefReachedMapTraits<T> > Create;
282
    struct SetReachedMap : public Dfs< Digraph, SetReachedMapTraits<T> > {
283
      typedef Dfs< Digraph, SetReachedMapTraits<T> > Create;
284 284
    };
285 285

	
286 286
    template <class T>
287
    struct DefProcessedMapTraits : public Traits {
287
    struct SetProcessedMapTraits : public Traits {
288 288
      typedef T ProcessedMap;
289 289
      static ProcessedMap *createProcessedMap(const Digraph &)
290 290
      {
291 291
        throw UninitializedParameter();
292 292
      }
293 293
    };
294 294
    ///\brief \ref named-templ-param "Named parameter" for setting
295 295
    ///\ref ProcessedMap type.
296 296
    ///
297 297
    ///\ref named-templ-param "Named parameter" for setting
298 298
    ///\ref ProcessedMap type.
299 299
    template <class T>
300
    struct DefProcessedMap : public Dfs< Digraph, DefProcessedMapTraits<T> > {
301
      typedef Dfs< Digraph, DefProcessedMapTraits<T> > Create;
300
    struct SetProcessedMap : public Dfs< Digraph, SetProcessedMapTraits<T> > {
301
      typedef Dfs< Digraph, SetProcessedMapTraits<T> > Create;
302 302
    };
303 303

	
304
    struct DefDigraphProcessedMapTraits : public Traits {
304
    struct SetStandardProcessedMapTraits : public Traits {
305 305
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
306 306
      static ProcessedMap *createProcessedMap(const Digraph &g)
307 307
      {
308 308
        return new ProcessedMap(g);
309 309
      }
310 310
    };
311 311
    ///\brief \ref named-templ-param "Named parameter" for setting
312 312
    ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
313 313
    ///
314 314
    ///\ref named-templ-param "Named parameter" for setting
315 315
    ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
316 316
    ///If you don't set it explicitly, it will be automatically allocated.
317
    template <class T>
318
    struct DefProcessedMapToBeDefaultMap :
319
      public Dfs< Digraph, DefDigraphProcessedMapTraits> {
320
      typedef Dfs< Digraph, DefDigraphProcessedMapTraits> Create;
317
    struct SetStandardProcessedMap :
318
      public Dfs< Digraph, SetStandardProcessedMapTraits > {
319
      typedef Dfs< Digraph, SetStandardProcessedMapTraits > Create;
321 320
    };
322 321

	
323 322
    ///@}
324 323

	
325 324
  public:
326 325

	
327 326
    ///Constructor.
328 327

	
329 328
    ///Constructor.
330 329
    ///\param g The digraph the algorithm runs on.
331 330
    Dfs(const Digraph &g) :
332 331
      G(&g),
333 332
      _pred(NULL), local_pred(false),
334 333
      _dist(NULL), local_dist(false),
335 334
      _reached(NULL), local_reached(false),
336 335
      _processed(NULL), local_processed(false)
337 336
    { }
338 337

	
339 338
    ///Destructor.
340 339
    ~Dfs()
341 340
    {
342 341
      if(local_pred) delete _pred;
343 342
      if(local_dist) delete _dist;
344 343
      if(local_reached) delete _reached;
345 344
      if(local_processed) delete _processed;
346 345
    }
347 346

	
348 347
    ///Sets the map that stores the predecessor arcs.
349 348

	
350 349
    ///Sets the map that stores the predecessor arcs.
351 350
    ///If you don't use this function before calling \ref run(),
352 351
    ///it will allocate one. The destructor deallocates this
353 352
    ///automatically allocated map, of course.
354 353
    ///\return <tt> (*this) </tt>
355 354
    Dfs &predMap(PredMap &m)
356 355
    {
357 356
      if(local_pred) {
358 357
        delete _pred;
359 358
        local_pred=false;
360 359
      }
361 360
      _pred = &m;
362 361
      return *this;
363 362
    }
364 363

	
365 364
    ///Sets the map that indicates which nodes are reached.
366 365

	
367 366
    ///Sets the map that indicates which nodes are reached.
368 367
    ///If you don't use this function before calling \ref run(),
369 368
    ///it will allocate one. The destructor deallocates this
370 369
    ///automatically allocated map, of course.
371 370
    ///\return <tt> (*this) </tt>
372 371
    Dfs &reachedMap(ReachedMap &m)
373 372
    {
374 373
      if(local_reached) {
375 374
        delete _reached;
376 375
        local_reached=false;
377 376
      }
378 377
      _reached = &m;
379 378
      return *this;
380 379
    }
381 380

	
382 381
    ///Sets the map that indicates which nodes are processed.
383 382

	
384 383
    ///Sets the map that indicates which nodes are processed.
385 384
    ///If you don't use this function before calling \ref run(),
386 385
    ///it will allocate one. The destructor deallocates this
387 386
    ///automatically allocated map, of course.
388 387
    ///\return <tt> (*this) </tt>
389 388
    Dfs &processedMap(ProcessedMap &m)
390 389
    {
391 390
      if(local_processed) {
392 391
        delete _processed;
393 392
        local_processed=false;
394 393
      }
395 394
      _processed = &m;
396 395
      return *this;
397 396
    }
398 397

	
399 398
    ///Sets the map that stores the distances of the nodes.
400 399

	
401 400
    ///Sets the map that stores the distances of the nodes calculated by
402 401
    ///the algorithm.
403 402
    ///If you don't use this function before calling \ref run(),
404 403
    ///it will allocate one. The destructor deallocates this
405 404
    ///automatically allocated map, of course.
406 405
    ///\return <tt> (*this) </tt>
407 406
    Dfs &distMap(DistMap &m)
408 407
    {
409 408
      if(local_dist) {
410 409
        delete _dist;
411 410
        local_dist=false;
412 411
      }
413 412
      _dist = &m;
414 413
      return *this;
415 414
    }
416 415

	
417 416
  public:
418 417

	
419 418
    ///\name Execution control
420 419
    ///The simplest way to execute the algorithm is to use
421 420
    ///one of the member functions called \ref lemon::Dfs::run() "run()".
422 421
    ///\n
423 422
    ///If you need more control on the execution, first you must call
424 423
    ///\ref lemon::Dfs::init() "init()", then you can add a source node
425 424
    ///with \ref lemon::Dfs::addSource() "addSource()".
426 425
    ///Finally \ref lemon::Dfs::start() "start()" will perform the
427 426
    ///actual path computation.
428 427

	
429 428
    ///@{
430 429

	
431 430
    ///Initializes the internal data structures.
432 431

	
433 432
    ///Initializes the internal data structures.
434 433
    ///
435 434
    void init()
436 435
    {
437 436
      create_maps();
438 437
      _stack.resize(countNodes(*G));
439 438
      _stack_head=-1;
440 439
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
441 440
        _pred->set(u,INVALID);
442 441
        _reached->set(u,false);
443 442
        _processed->set(u,false);
444 443
      }
445 444
    }
446 445

	
447 446
    ///Adds a new source node.
448 447

	
449 448
    ///Adds a new source node to the set of nodes to be processed.
450 449
    ///
451 450
    ///\pre The stack must be empty. (Otherwise the algorithm gives
452 451
    ///false results.)
453 452
    ///
454 453
    ///\warning Distances will be wrong (or at least strange) in case of
455 454
    ///multiple sources.
456 455
    void addSource(Node s)
457 456
    {
458 457
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
459 458
      if(!(*_reached)[s])
460 459
        {
461 460
          _reached->set(s,true);
462 461
          _pred->set(s,INVALID);
463 462
          OutArcIt e(*G,s);
464 463
          if(e!=INVALID) {
465 464
            _stack[++_stack_head]=e;
466 465
            _dist->set(s,_stack_head);
467 466
          }
468 467
          else {
469 468
            _processed->set(s,true);
470 469
            _dist->set(s,0);
471 470
          }
472 471
        }
473 472
    }
474 473

	
475 474
    ///Processes the next arc.
476 475

	
477 476
    ///Processes the next arc.
478 477
    ///
479 478
    ///\return The processed arc.
480 479
    ///
481 480
    ///\pre The stack must not be empty.
482 481
    Arc processNextArc()
483 482
    {
484 483
      Node m;
485 484
      Arc e=_stack[_stack_head];
486 485
      if(!(*_reached)[m=G->target(e)]) {
487 486
        _pred->set(m,e);
488 487
        _reached->set(m,true);
489 488
        ++_stack_head;
490 489
        _stack[_stack_head] = OutArcIt(*G, m);
491 490
        _dist->set(m,_stack_head);
492 491
      }
493 492
      else {
494 493
        m=G->source(e);
495 494
        ++_stack[_stack_head];
496 495
      }
497 496
      while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
498 497
        _processed->set(m,true);
499 498
        --_stack_head;
500 499
        if(_stack_head>=0) {
501 500
          m=G->source(_stack[_stack_head]);
502 501
          ++_stack[_stack_head];
503 502
        }
504 503
      }
505 504
      return e;
506 505
    }
507 506

	
508 507
    ///Next arc to be processed.
509 508

	
510 509
    ///Next arc to be processed.
511 510
    ///
512 511
    ///\return The next arc to be processed or \c INVALID if the stack
513 512
    ///is empty.
514 513
    OutArcIt nextArc() const
515 514
    {
516 515
      return _stack_head>=0?_stack[_stack_head]:INVALID;
517 516
    }
518 517

	
519 518
    ///\brief Returns \c false if there are nodes
520 519
    ///to be processed.
521 520
    ///
522 521
    ///Returns \c false if there are nodes
523 522
    ///to be processed in the queue (stack).
524 523
    bool emptyQueue() const { return _stack_head<0; }
525 524

	
526 525
    ///Returns the number of the nodes to be processed.
527 526

	
528 527
    ///Returns the number of the nodes to be processed in the queue (stack).
529 528
    int queueSize() const { return _stack_head+1; }
530 529

	
531 530
    ///Executes the algorithm.
532 531

	
533 532
    ///Executes the algorithm.
534 533
    ///
535 534
    ///This method runs the %DFS algorithm from the root node
536 535
    ///in order to compute the DFS path to each node.
537 536
    ///
538 537
    /// The algorithm computes
539 538
    ///- the %DFS tree,
540 539
    ///- the distance of each node from the root in the %DFS tree.
541 540
    ///
542 541
    ///\pre init() must be called and a root node should be
543 542
    ///added with addSource() before using this function.
544 543
    ///
545 544
    ///\note <tt>d.start()</tt> is just a shortcut of the following code.
546 545
    ///\code
547 546
    ///  while ( !d.emptyQueue() ) {
548 547
    ///    d.processNextArc();
549 548
    ///  }
550 549
    ///\endcode
551 550
    void start()
552 551
    {
553 552
      while ( !emptyQueue() ) processNextArc();
554 553
    }
555 554

	
556 555
    ///Executes the algorithm until the given target node is reached.
557 556

	
558 557
    ///Executes the algorithm until the given target node is reached.
559 558
    ///
560 559
    ///This method runs the %DFS algorithm from the root node
561 560
    ///in order to compute the DFS path to \c dest.
562 561
    ///
563 562
    ///The algorithm computes
564 563
    ///- the %DFS path to \c dest,
565 564
    ///- the distance of \c dest from the root in the %DFS tree.
566 565
    ///
567 566
    ///\pre init() must be called and a root node should be
568 567
    ///added with addSource() before using this function.
569 568
    void start(Node dest)
570 569
    {
571 570
      while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest )
572 571
        processNextArc();
573 572
    }
574 573

	
575 574
    ///Executes the algorithm until a condition is met.
576 575

	
577 576
    ///Executes the algorithm until a condition is met.
578 577
    ///
579 578
    ///This method runs the %DFS algorithm from the root node
580 579
    ///until an arc \c a with <tt>am[a]</tt> true is found.
581 580
    ///
582 581
    ///\param am A \c bool (or convertible) arc map. The algorithm
583 582
    ///will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
584 583
    ///
585 584
    ///\return The reached arc \c a with <tt>am[a]</tt> true or
586 585
    ///\c INVALID if no such arc was found.
587 586
    ///
588 587
    ///\pre init() must be called and a root node should be
589 588
    ///added with addSource() before using this function.
590 589
    ///
591 590
    ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
592 591
    ///not a node map.
593 592
    template<class ArcBoolMap>
594 593
    Arc start(const ArcBoolMap &am)
595 594
    {
596 595
      while ( !emptyQueue() && !am[_stack[_stack_head]] )
597 596
        processNextArc();
598 597
      return emptyQueue() ? INVALID : _stack[_stack_head];
599 598
    }
600 599

	
601 600
    ///Runs the algorithm from the given node.
602 601

	
603 602
    ///This method runs the %DFS algorithm from node \c s
604 603
    ///in order to compute the DFS path to each node.
605 604
    ///
606 605
    ///The algorithm computes
607 606
    ///- the %DFS tree,
608 607
    ///- the distance of each node from the root in the %DFS tree.
609 608
    ///
610 609
    ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
611 610
    ///\code
612 611
    ///  d.init();
613 612
    ///  d.addSource(s);
614 613
    ///  d.start();
615 614
    ///\endcode
616 615
    void run(Node s) {
617 616
      init();
618 617
      addSource(s);
619 618
      start();
620 619
    }
621 620

	
622 621
    ///Finds the %DFS path between \c s and \c t.
623 622

	
624 623
    ///This method runs the %DFS algorithm from node \c s
625 624
    ///in order to compute the DFS path to \c t.
626 625
    ///
627 626
    ///\return The length of the <tt>s</tt>--<tt>t</tt> DFS path,
628 627
    ///if \c t is reachable form \c s, \c 0 otherwise.
629 628
    ///
630 629
    ///\note Apart from the return value, <tt>d.run(s,t)</tt> is
631 630
    ///just a shortcut of the following code.
632 631
    ///\code
633 632
    ///  d.init();
634 633
    ///  d.addSource(s);
635 634
    ///  d.start(t);
636 635
    ///\endcode
637 636
    int run(Node s,Node t) {
638 637
      init();
639 638
      addSource(s);
640 639
      start(t);
641 640
      return reached(t)?_stack_head+1:0;
642 641
    }
643 642

	
644 643
    ///Runs the algorithm to visit all nodes in the digraph.
645 644

	
646 645
    ///This method runs the %DFS algorithm in order to compute the
647 646
    ///%DFS path to each node.
648 647
    ///
649 648
    ///The algorithm computes
650 649
    ///- the %DFS tree,
651 650
    ///- the distance of each node from the root in the %DFS tree.
652 651
    ///
653 652
    ///\note <tt>d.run()</tt> is just a shortcut of the following code.
654 653
    ///\code
655 654
    ///  d.init();
656 655
    ///  for (NodeIt n(digraph); n != INVALID; ++n) {
657 656
    ///    if (!d.reached(n)) {
658 657
    ///      d.addSource(n);
659 658
    ///      d.start();
660 659
    ///    }
661 660
    ///  }
662 661
    ///\endcode
663 662
    void run() {
664 663
      init();
665 664
      for (NodeIt it(*G); it != INVALID; ++it) {
666 665
        if (!reached(it)) {
667 666
          addSource(it);
668 667
          start();
669 668
        }
670 669
      }
671 670
    }
672 671

	
673 672
    ///@}
674 673

	
675 674
    ///\name Query Functions
676 675
    ///The result of the %DFS algorithm can be obtained using these
677 676
    ///functions.\n
678 677
    ///Either \ref lemon::Dfs::run() "run()" or \ref lemon::Dfs::start()
679 678
    ///"start()" must be called before using them.
680 679

	
681 680
    ///@{
682 681

	
683 682
    ///The DFS path to a node.
684 683

	
685 684
    ///Returns the DFS path to a node.
686 685
    ///
687 686
    ///\warning \c t should be reachable from the root.
688 687
    ///
689 688
    ///\pre Either \ref run() or \ref start() must be called before
690 689
    ///using this function.
691 690
    Path path(Node t) const { return Path(*G, *_pred, t); }
692 691

	
693 692
    ///The distance of a node from the root.
694 693

	
695 694
    ///Returns the distance of a node from the root.
696 695
    ///
697 696
    ///\warning If node \c v is not reachable from the root, then
698 697
    ///the return value of this function is undefined.
699 698
    ///
700 699
    ///\pre Either \ref run() or \ref start() must be called before
701 700
    ///using this function.
702 701
    int dist(Node v) const { return (*_dist)[v]; }
703 702

	
704 703
    ///Returns the 'previous arc' of the %DFS tree for a node.
705 704

	
706 705
    ///This function returns the 'previous arc' of the %DFS tree for the
707 706
    ///node \c v, i.e. it returns the last arc of a %DFS path from the
708 707
    ///root to \c v. It is \c INVALID
709 708
    ///if \c v is not reachable from the root(s) or if \c v is a root.
710 709
    ///
711 710
    ///The %DFS tree used here is equal to the %DFS tree used in
712 711
    ///\ref predNode().
713 712
    ///
714 713
    ///\pre Either \ref run() or \ref start() must be called before using
715 714
    ///this function.
716 715
    Arc predArc(Node v) const { return (*_pred)[v];}
717 716

	
718 717
    ///Returns the 'previous node' of the %DFS tree.
719 718

	
720 719
    ///This function returns the 'previous node' of the %DFS
721 720
    ///tree for the node \c v, i.e. it returns the last but one node
722 721
    ///from a %DFS path from the root to \c v. It is \c INVALID
723 722
    ///if \c v is not reachable from the root(s) or if \c v is a root.
724 723
    ///
725 724
    ///The %DFS tree used here is equal to the %DFS tree used in
726 725
    ///\ref predArc().
727 726
    ///
728 727
    ///\pre Either \ref run() or \ref start() must be called before
729 728
    ///using this function.
730 729
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
731 730
                                  G->source((*_pred)[v]); }
732 731

	
733 732
    ///\brief Returns a const reference to the node map that stores the
734 733
    ///distances of the nodes.
735 734
    ///
736 735
    ///Returns a const reference to the node map that stores the
737 736
    ///distances of the nodes calculated by the algorithm.
738 737
    ///
739 738
    ///\pre Either \ref run() or \ref init()
740 739
    ///must be called before using this function.
741 740
    const DistMap &distMap() const { return *_dist;}
742 741

	
743 742
    ///\brief Returns a const reference to the node map that stores the
744 743
    ///predecessor arcs.
745 744
    ///
746 745
    ///Returns a const reference to the node map that stores the predecessor
747 746
    ///arcs, which form the DFS tree.
748 747
    ///
749 748
    ///\pre Either \ref run() or \ref init()
750 749
    ///must be called before using this function.
751 750
    const PredMap &predMap() const { return *_pred;}
752 751

	
753 752
    ///Checks if a node is reachable from the root(s).
754 753

	
755 754
    ///Returns \c true if \c v is reachable from the root(s).
756 755
    ///\pre Either \ref run() or \ref start()
757 756
    ///must be called before using this function.
758 757
    bool reached(Node v) const { return (*_reached)[v]; }
759 758

	
760 759
    ///@}
761 760
  };
762 761

	
763 762
  ///Default traits class of dfs() function.
764 763

	
765 764
  ///Default traits class of dfs() function.
766 765
  ///\tparam GR Digraph type.
767 766
  template<class GR>
768 767
  struct DfsWizardDefaultTraits
769 768
  {
770 769
    ///The type of the digraph the algorithm runs on.
771 770
    typedef GR Digraph;
772 771

	
773 772
    ///\brief The type of the map that stores the predecessor
774 773
    ///arcs of the %DFS paths.
775 774
    ///
776 775
    ///The type of the map that stores the predecessor
777 776
    ///arcs of the %DFS paths.
778 777
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
779 778
    ///
780 779
    typedef NullMap<typename Digraph::Node,typename Digraph::Arc> PredMap;
781 780
    ///Instantiates a \ref PredMap.
782 781

	
783 782
    ///This function instantiates a \ref PredMap.
784 783
    ///\param g is the digraph, to which we would like to define the
785 784
    ///\ref PredMap.
786 785
    ///\todo The digraph alone may be insufficient to initialize
787 786
#ifdef DOXYGEN
788 787
    static PredMap *createPredMap(const Digraph &g)
789 788
#else
790 789
    static PredMap *createPredMap(const Digraph &)
791 790
#endif
792 791
    {
793 792
      return new PredMap();
794 793
    }
795 794

	
796 795
    ///The type of the map that indicates which nodes are processed.
797 796

	
798 797
    ///The type of the map that indicates which nodes are processed.
799 798
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
800 799
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
801 800
    ///Instantiates a \ref ProcessedMap.
802 801

	
803 802
    ///This function instantiates a \ref ProcessedMap.
804 803
    ///\param g is the digraph, to which
805 804
    ///we would like to define the \ref ProcessedMap.
806 805
#ifdef DOXYGEN
807 806
    static ProcessedMap *createProcessedMap(const Digraph &g)
808 807
#else
809 808
    static ProcessedMap *createProcessedMap(const Digraph &)
810 809
#endif
811 810
    {
812 811
      return new ProcessedMap();
813 812
    }
814 813

	
815 814
    ///The type of the map that indicates which nodes are reached.
816 815

	
817 816
    ///The type of the map that indicates which nodes are reached.
818 817
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
819 818
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
820 819
    ///Instantiates a \ref ReachedMap.
821 820

	
822 821
    ///This function instantiates a \ref ReachedMap.
823 822
    ///\param g is the digraph, to which
824 823
    ///we would like to define the \ref ReachedMap.
825 824
    static ReachedMap *createReachedMap(const Digraph &g)
826 825
    {
827 826
      return new ReachedMap(g);
828 827
    }
829 828

	
830 829
    ///The type of the map that stores the distances of the nodes.
831 830

	
832 831
    ///The type of the map that stores the distances of the nodes.
833 832
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
834 833
    ///
835 834
    typedef NullMap<typename Digraph::Node,int> DistMap;
836 835
    ///Instantiates a \ref DistMap.
837 836

	
838 837
    ///This function instantiates a \ref DistMap.
839 838
    ///\param g is the digraph, to which we would like to define
840 839
    ///the \ref DistMap
841 840
#ifdef DOXYGEN
842 841
    static DistMap *createDistMap(const Digraph &g)
843 842
#else
844 843
    static DistMap *createDistMap(const Digraph &)
845 844
#endif
846 845
    {
847 846
      return new DistMap();
848 847
    }
849 848
  };
850 849

	
851 850
  /// Default traits class used by \ref DfsWizard
852 851

	
853 852
  /// To make it easier to use Dfs algorithm
854 853
  /// we have created a wizard class.
855 854
  /// This \ref DfsWizard class needs default traits,
856 855
  /// as well as the \ref Dfs class.
857 856
  /// The \ref DfsWizardBase is a class to be the default traits of the
858 857
  /// \ref DfsWizard class.
859 858
  template<class GR>
860 859
  class DfsWizardBase : public DfsWizardDefaultTraits<GR>
861 860
  {
862 861

	
863 862
    typedef DfsWizardDefaultTraits<GR> Base;
864 863
  protected:
865 864
    //The type of the nodes in the digraph.
866 865
    typedef typename Base::Digraph::Node Node;
867 866

	
868 867
    //Pointer to the digraph the algorithm runs on.
869 868
    void *_g;
870 869
    //Pointer to the map of reached nodes.
871 870
    void *_reached;
872 871
    //Pointer to the map of processed nodes.
873 872
    void *_processed;
874 873
    //Pointer to the map of predecessors arcs.
875 874
    void *_pred;
876 875
    //Pointer to the map of distances.
877 876
    void *_dist;
878 877
    //Pointer to the source node.
879 878
    Node _source;
880 879

	
881 880
    public:
882 881
    /// Constructor.
883 882

	
884 883
    /// This constructor does not require parameters, therefore it initiates
885 884
    /// all of the attributes to default values (0, INVALID).
886 885
    DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
887 886
                      _dist(0), _source(INVALID) {}
888 887

	
889 888
    /// Constructor.
890 889

	
891 890
    /// This constructor requires some parameters,
892 891
    /// listed in the parameters list.
893 892
    /// Others are initiated to 0.
894 893
    /// \param g The digraph the algorithm runs on.
895 894
    /// \param s The source node.
896 895
    DfsWizardBase(const GR &g, Node s=INVALID) :
897 896
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
898 897
      _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
899 898

	
900 899
  };
901 900

	
902 901
  /// Auxiliary class for the function type interface of DFS algorithm.
903 902

	
904 903
  /// This auxiliary class is created to implement the function type
905 904
  /// interface of \ref Dfs algorithm. It uses the functions and features
906 905
  /// of the plain \ref Dfs, but it is much simpler to use it.
907 906
  /// It should only be used through the \ref dfs() function, which makes
908 907
  /// it easier to use the algorithm.
909 908
  ///
910 909
  /// Simplicity means that the way to change the types defined
911 910
  /// in the traits class is based on functions that returns the new class
912 911
  /// and not on templatable built-in classes.
913 912
  /// When using the plain \ref Dfs
914 913
  /// the new class with the modified type comes from
915 914
  /// the original class by using the ::
916 915
  /// operator. In the case of \ref DfsWizard only
917 916
  /// a function have to be called, and it will
918 917
  /// return the needed class.
919 918
  ///
920 919
  /// It does not have own \ref run() method. When its \ref run() method
921 920
  /// is called, it initiates a plain \ref Dfs object, and calls the
922 921
  /// \ref Dfs::run() method of it.
923 922
  template<class TR>
924 923
  class DfsWizard : public TR
925 924
  {
926 925
    typedef TR Base;
927 926

	
928 927
    ///The type of the digraph the algorithm runs on.
929 928
    typedef typename TR::Digraph Digraph;
930 929

	
931 930
    typedef typename Digraph::Node Node;
932 931
    typedef typename Digraph::NodeIt NodeIt;
933 932
    typedef typename Digraph::Arc Arc;
934 933
    typedef typename Digraph::OutArcIt OutArcIt;
935 934

	
936 935
    ///\brief The type of the map that stores the predecessor
937 936
    ///arcs of the shortest paths.
938 937
    typedef typename TR::PredMap PredMap;
939 938
    ///\brief The type of the map that stores the distances of the nodes.
940 939
    typedef typename TR::DistMap DistMap;
941 940
    ///\brief The type of the map that indicates which nodes are reached.
942 941
    typedef typename TR::ReachedMap ReachedMap;
943 942
    ///\brief The type of the map that indicates which nodes are processed.
944 943
    typedef typename TR::ProcessedMap ProcessedMap;
945 944

	
946 945
  public:
947 946

	
948 947
    /// Constructor.
949 948
    DfsWizard() : TR() {}
950 949

	
951 950
    /// Constructor that requires parameters.
952 951

	
953 952
    /// Constructor that requires parameters.
954 953
    /// These parameters will be the default values for the traits class.
955 954
    DfsWizard(const Digraph &g, Node s=INVALID) :
956 955
      TR(g,s) {}
957 956

	
958 957
    ///Copy constructor
959 958
    DfsWizard(const TR &b) : TR(b) {}
960 959

	
961 960
    ~DfsWizard() {}
962 961

	
963 962
    ///Runs DFS algorithm from a source node.
964 963

	
965 964
    ///Runs DFS algorithm from a source node.
966 965
    ///The node can be given with the \ref source() function.
967 966
    void run()
968 967
    {
969 968
      if(Base::_source==INVALID) throw UninitializedParameter();
970 969
      Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
971 970
      if(Base::_reached)
972 971
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
973 972
      if(Base::_processed)
974 973
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
975 974
      if(Base::_pred)
976 975
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
977 976
      if(Base::_dist)
978 977
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
979 978
      alg.run(Base::_source);
980 979
    }
981 980

	
982 981
    ///Runs DFS algorithm from the given node.
983 982

	
984 983
    ///Runs DFS algorithm from the given node.
985 984
    ///\param s is the given source.
986 985
    void run(Node s)
987 986
    {
988 987
      Base::_source=s;
989 988
      run();
990 989
    }
991 990

	
992 991
    /// Sets the source node, from which the Dfs algorithm runs.
993 992

	
994 993
    /// Sets the source node, from which the Dfs algorithm runs.
995 994
    /// \param s is the source node.
996 995
    DfsWizard<TR> &source(Node s)
997 996
    {
998 997
      Base::_source=s;
999 998
      return *this;
1000 999
    }
1001 1000

	
1002 1001
    template<class T>
1003
    struct DefPredMapBase : public Base {
1002
    struct SetPredMapBase : public Base {
1004 1003
      typedef T PredMap;
1005 1004
      static PredMap *createPredMap(const Digraph &) { return 0; };
1006
      DefPredMapBase(const TR &b) : TR(b) {}
1005
      SetPredMapBase(const TR &b) : TR(b) {}
1007 1006
    };
1008 1007
    ///\brief \ref named-templ-param "Named parameter"
1009 1008
    ///for setting \ref PredMap object.
1010 1009
    ///
1011 1010
    ///\ref named-templ-param "Named parameter"
1012 1011
    ///for setting \ref PredMap object.
1013 1012
    template<class T>
1014
    DfsWizard<DefPredMapBase<T> > predMap(const T &t)
1013
    DfsWizard<SetPredMapBase<T> > predMap(const T &t)
1015 1014
    {
1016 1015
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1017
      return DfsWizard<DefPredMapBase<T> >(*this);
1016
      return DfsWizard<SetPredMapBase<T> >(*this);
1018 1017
    }
1019 1018

	
1020 1019
    template<class T>
1021
    struct DefReachedMapBase : public Base {
1020
    struct SetReachedMapBase : public Base {
1022 1021
      typedef T ReachedMap;
1023 1022
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1024
      DefReachedMapBase(const TR &b) : TR(b) {}
1023
      SetReachedMapBase(const TR &b) : TR(b) {}
1025 1024
    };
1026 1025
    ///\brief \ref named-templ-param "Named parameter"
1027 1026
    ///for setting \ref ReachedMap object.
1028 1027
    ///
1029 1028
    /// \ref named-templ-param "Named parameter"
1030 1029
    ///for setting \ref ReachedMap object.
1031 1030
    template<class T>
1032
    DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1031
    DfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1033 1032
    {
1034 1033
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1035
      return DfsWizard<DefReachedMapBase<T> >(*this);
1034
      return DfsWizard<SetReachedMapBase<T> >(*this);
1036 1035
    }
1037 1036

	
1038 1037
    template<class T>
1039
    struct DefProcessedMapBase : public Base {
1038
    struct SetProcessedMapBase : public Base {
1040 1039
      typedef T ProcessedMap;
1041 1040
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1042
      DefProcessedMapBase(const TR &b) : TR(b) {}
1041
      SetProcessedMapBase(const TR &b) : TR(b) {}
1043 1042
    };
1044 1043
    ///\brief \ref named-templ-param "Named parameter"
1045 1044
    ///for setting \ref ProcessedMap object.
1046 1045
    ///
1047 1046
    /// \ref named-templ-param "Named parameter"
1048 1047
    ///for setting \ref ProcessedMap object.
1049 1048
    template<class T>
1050
    DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1049
    DfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1051 1050
    {
1052 1051
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1053
      return DfsWizard<DefProcessedMapBase<T> >(*this);
1052
      return DfsWizard<SetProcessedMapBase<T> >(*this);
1054 1053
    }
1055 1054

	
1056 1055
    template<class T>
1057
    struct DefDistMapBase : public Base {
1056
    struct SetDistMapBase : public Base {
1058 1057
      typedef T DistMap;
1059 1058
      static DistMap *createDistMap(const Digraph &) { return 0; };
1060
      DefDistMapBase(const TR &b) : TR(b) {}
1059
      SetDistMapBase(const TR &b) : TR(b) {}
1061 1060
    };
1062 1061
    ///\brief \ref named-templ-param "Named parameter"
1063 1062
    ///for setting \ref DistMap object.
1064 1063
    ///
1065 1064
    ///\ref named-templ-param "Named parameter"
1066 1065
    ///for setting \ref DistMap object.
1067 1066
    template<class T>
1068
    DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1067
    DfsWizard<SetDistMapBase<T> > distMap(const T &t)
1069 1068
    {
1070 1069
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1071
      return DfsWizard<DefDistMapBase<T> >(*this);
1070
      return DfsWizard<SetDistMapBase<T> >(*this);
1072 1071
    }
1073 1072

	
1074 1073
  };
1075 1074

	
1076 1075
  ///Function type interface for Dfs algorithm.
1077 1076

	
1078 1077
  ///\ingroup search
1079 1078
  ///Function type interface for Dfs algorithm.
1080 1079
  ///
1081 1080
  ///This function also has several
1082 1081
  ///\ref named-templ-func-param "named parameters",
1083 1082
  ///they are declared as the members of class \ref DfsWizard.
1084 1083
  ///The following
1085 1084
  ///example shows how to use these parameters.
1086 1085
  ///\code
1087 1086
  ///  dfs(g,source).predMap(preds).run();
1088 1087
  ///\endcode
1089 1088
  ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1090 1089
  ///to the end of the parameter list.
1091 1090
  ///\sa DfsWizard
1092 1091
  ///\sa Dfs
1093 1092
  template<class GR>
1094 1093
  DfsWizard<DfsWizardBase<GR> >
1095 1094
  dfs(const GR &g,typename GR::Node s=INVALID)
1096 1095
  {
1097 1096
    return DfsWizard<DfsWizardBase<GR> >(g,s);
1098 1097
  }
1099 1098

	
1100 1099
#ifdef DOXYGEN
1101 1100
  /// \brief Visitor class for DFS.
1102 1101
  ///
1103 1102
  /// This class defines the interface of the DfsVisit events, and
1104 1103
  /// it could be the base of a real visitor class.
1105 1104
  template <typename _Digraph>
1106 1105
  struct DfsVisitor {
1107 1106
    typedef _Digraph Digraph;
1108 1107
    typedef typename Digraph::Arc Arc;
1109 1108
    typedef typename Digraph::Node Node;
1110 1109
    /// \brief Called for the source node of the DFS.
1111 1110
    ///
1112 1111
    /// This function is called for the source node of the DFS.
1113 1112
    void start(const Node& node) {}
1114 1113
    /// \brief Called when the source node is leaved.
1115 1114
    ///
1116 1115
    /// This function is called when the source node is leaved.
1117 1116
    void stop(const Node& node) {}
1118 1117
    /// \brief Called when a node is reached first time.
1119 1118
    ///
1120 1119
    /// This function is called when a node is reached first time.
1121 1120
    void reach(const Node& node) {}
1122 1121
    /// \brief Called when an arc reaches a new node.
1123 1122
    ///
1124 1123
    /// This function is called when the DFS finds an arc whose target node
1125 1124
    /// is not reached yet.
1126 1125
    void discover(const Arc& arc) {}
1127 1126
    /// \brief Called when an arc is examined but its target node is
1128 1127
    /// already discovered.
1129 1128
    ///
1130 1129
    /// This function is called when an arc is examined but its target node is
1131 1130
    /// already discovered.
1132 1131
    void examine(const Arc& arc) {}
1133 1132
    /// \brief Called when the DFS steps back from a node.
1134 1133
    ///
1135 1134
    /// This function is called when the DFS steps back from a node.
1136 1135
    void leave(const Node& node) {}
1137 1136
    /// \brief Called when the DFS steps back on an arc.
1138 1137
    ///
1139 1138
    /// This function is called when the DFS steps back on an arc.
1140 1139
    void backtrack(const Arc& arc) {}
1141 1140
  };
1142 1141
#else
1143 1142
  template <typename _Digraph>
1144 1143
  struct DfsVisitor {
1145 1144
    typedef _Digraph Digraph;
1146 1145
    typedef typename Digraph::Arc Arc;
1147 1146
    typedef typename Digraph::Node Node;
1148 1147
    void start(const Node&) {}
1149 1148
    void stop(const Node&) {}
1150 1149
    void reach(const Node&) {}
1151 1150
    void discover(const Arc&) {}
1152 1151
    void examine(const Arc&) {}
1153 1152
    void leave(const Node&) {}
1154 1153
    void backtrack(const Arc&) {}
1155 1154

	
1156 1155
    template <typename _Visitor>
1157 1156
    struct Constraints {
1158 1157
      void constraints() {
1159 1158
        Arc arc;
1160 1159
        Node node;
1161 1160
        visitor.start(node);
1162 1161
        visitor.stop(arc);
1163 1162
        visitor.reach(node);
1164 1163
        visitor.discover(arc);
1165 1164
        visitor.examine(arc);
1166 1165
        visitor.leave(node);
1167 1166
        visitor.backtrack(arc);
1168 1167
      }
1169 1168
      _Visitor& visitor;
1170 1169
    };
1171 1170
  };
1172 1171
#endif
1173 1172

	
1174 1173
  /// \brief Default traits class of DfsVisit class.
1175 1174
  ///
1176 1175
  /// Default traits class of DfsVisit class.
1177 1176
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1178 1177
  template<class _Digraph>
1179 1178
  struct DfsVisitDefaultTraits {
1180 1179

	
1181 1180
    /// \brief The type of the digraph the algorithm runs on.
1182 1181
    typedef _Digraph Digraph;
1183 1182

	
1184 1183
    /// \brief The type of the map that indicates which nodes are reached.
1185 1184
    ///
1186 1185
    /// The type of the map that indicates which nodes are reached.
1187 1186
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1188 1187
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1189 1188

	
1190 1189
    /// \brief Instantiates a \ref ReachedMap.
1191 1190
    ///
1192 1191
    /// This function instantiates a \ref ReachedMap.
1193 1192
    /// \param digraph is the digraph, to which
1194 1193
    /// we would like to define the \ref ReachedMap.
1195 1194
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1196 1195
      return new ReachedMap(digraph);
1197 1196
    }
1198 1197

	
1199 1198
  };
1200 1199

	
1201 1200
  /// \ingroup search
1202 1201
  ///
1203 1202
  /// \brief %DFS algorithm class with visitor interface.
1204 1203
  ///
1205 1204
  /// This class provides an efficient implementation of the %DFS algorithm
1206 1205
  /// with visitor interface.
1207 1206
  ///
1208 1207
  /// The %DfsVisit class provides an alternative interface to the Dfs
1209 1208
  /// class. It works with callback mechanism, the DfsVisit object calls
1210 1209
  /// the member functions of the \c Visitor class on every DFS event.
1211 1210
  ///
1212 1211
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1213 1212
  /// The default value is
1214 1213
  /// \ref ListDigraph. The value of _Digraph is not used directly by
1215 1214
  /// \ref DfsVisit, it is only passed to \ref DfsVisitDefaultTraits.
1216 1215
  /// \tparam _Visitor The Visitor type that is used by the algorithm.
1217 1216
  /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty visitor, which
1218 1217
  /// does not observe the DFS events. If you want to observe the DFS
1219 1218
  /// events, you should implement your own visitor class.
1220 1219
  /// \tparam _Traits Traits class to set various data types used by the
1221 1220
  /// algorithm. The default traits class is
1222 1221
  /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>".
1223 1222
  /// See \ref DfsVisitDefaultTraits for the documentation of
1224 1223
  /// a DFS visit traits class.
1225 1224
#ifdef DOXYGEN
1226 1225
  template <typename _Digraph, typename _Visitor, typename _Traits>
1227 1226
#else
1228 1227
  template <typename _Digraph = ListDigraph,
1229 1228
            typename _Visitor = DfsVisitor<_Digraph>,
1230 1229
            typename _Traits = DfsDefaultTraits<_Digraph> >
1231 1230
#endif
1232 1231
  class DfsVisit {
1233 1232
  public:
1234 1233

	
1235 1234
    /// \brief \ref Exception for uninitialized parameters.
1236 1235
    ///
1237 1236
    /// This error represents problems in the initialization
1238 1237
    /// of the parameters of the algorithm.
1239 1238
    class UninitializedParameter : public lemon::UninitializedParameter {
1240 1239
    public:
1241 1240
      virtual const char* what() const throw()
1242 1241
      {
1243 1242
        return "lemon::DfsVisit::UninitializedParameter";
1244 1243
      }
1245 1244
    };
1246 1245

	
1247 1246
    ///The traits class.
1248 1247
    typedef _Traits Traits;
1249 1248

	
1250 1249
    ///The type of the digraph the algorithm runs on.
1251 1250
    typedef typename Traits::Digraph Digraph;
1252 1251

	
1253 1252
    ///The visitor type used by the algorithm.
1254 1253
    typedef _Visitor Visitor;
1255 1254

	
1256 1255
    ///The type of the map that indicates which nodes are reached.
1257 1256
    typedef typename Traits::ReachedMap ReachedMap;
1258 1257

	
1259 1258
  private:
1260 1259

	
1261 1260
    typedef typename Digraph::Node Node;
1262 1261
    typedef typename Digraph::NodeIt NodeIt;
1263 1262
    typedef typename Digraph::Arc Arc;
1264 1263
    typedef typename Digraph::OutArcIt OutArcIt;
1265 1264

	
1266 1265
    //Pointer to the underlying digraph.
1267 1266
    const Digraph *_digraph;
1268 1267
    //Pointer to the visitor object.
1269 1268
    Visitor *_visitor;
1270 1269
    //Pointer to the map of reached status of the nodes.
1271 1270
    ReachedMap *_reached;
1272 1271
    //Indicates if _reached is locally allocated (true) or not.
1273 1272
    bool local_reached;
1274 1273

	
1275 1274
    std::vector<typename Digraph::Arc> _stack;
1276 1275
    int _stack_head;
1277 1276

	
1278 1277
    ///Creates the maps if necessary.
1279 1278
    ///\todo Better memory allocation (instead of new).
1280 1279
    void create_maps() {
1281 1280
      if(!_reached) {
1282 1281
        local_reached = true;
1283 1282
        _reached = Traits::createReachedMap(*_digraph);
1284 1283
      }
1285 1284
    }
1286 1285

	
1287 1286
  protected:
1288 1287

	
1289 1288
    DfsVisit() {}
1290 1289

	
1291 1290
  public:
1292 1291

	
1293 1292
    typedef DfsVisit Create;
1294 1293

	
1295 1294
    /// \name Named template parameters
1296 1295

	
1297 1296
    ///@{
1298 1297
    template <class T>
1299
    struct DefReachedMapTraits : public Traits {
1298
    struct SetReachedMapTraits : public Traits {
1300 1299
      typedef T ReachedMap;
1301 1300
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1302 1301
        throw UninitializedParameter();
1303 1302
      }
1304 1303
    };
1305 1304
    /// \brief \ref named-templ-param "Named parameter" for setting
1306 1305
    /// ReachedMap type.
1307 1306
    ///
1308 1307
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1309 1308
    template <class T>
1310
    struct DefReachedMap : public DfsVisit< Digraph, Visitor,
1311
                                            DefReachedMapTraits<T> > {
1312
      typedef DfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create;
1309
    struct SetReachedMap : public DfsVisit< Digraph, Visitor,
1310
                                            SetReachedMapTraits<T> > {
1311
      typedef DfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1313 1312
    };
1314 1313
    ///@}
1315 1314

	
1316 1315
  public:
1317 1316

	
1318 1317
    /// \brief Constructor.
1319 1318
    ///
1320 1319
    /// Constructor.
1321 1320
    ///
1322 1321
    /// \param digraph The digraph the algorithm runs on.
1323 1322
    /// \param visitor The visitor object of the algorithm.
1324 1323
    DfsVisit(const Digraph& digraph, Visitor& visitor)
1325 1324
      : _digraph(&digraph), _visitor(&visitor),
1326 1325
        _reached(0), local_reached(false) {}
1327 1326

	
1328 1327
    /// \brief Destructor.
1329 1328
    ~DfsVisit() {
1330 1329
      if(local_reached) delete _reached;
1331 1330
    }
1332 1331

	
1333 1332
    /// \brief Sets the map that indicates which nodes are reached.
1334 1333
    ///
1335 1334
    /// Sets the map that indicates which nodes are reached.
1336 1335
    /// If you don't use this function before calling \ref run(),
1337 1336
    /// it will allocate one. The destructor deallocates this
1338 1337
    /// automatically allocated map, of course.
1339 1338
    /// \return <tt> (*this) </tt>
1340 1339
    DfsVisit &reachedMap(ReachedMap &m) {
1341 1340
      if(local_reached) {
1342 1341
        delete _reached;
1343 1342
        local_reached=false;
1344 1343
      }
1345 1344
      _reached = &m;
1346 1345
      return *this;
1347 1346
    }
1348 1347

	
1349 1348
  public:
1350 1349

	
1351 1350
    /// \name Execution control
1352 1351
    /// The simplest way to execute the algorithm is to use
1353 1352
    /// one of the member functions called \ref lemon::DfsVisit::run()
1354 1353
    /// "run()".
1355 1354
    /// \n
1356 1355
    /// If you need more control on the execution, first you must call
1357 1356
    /// \ref lemon::DfsVisit::init() "init()", then you can add several
1358 1357
    /// source nodes with \ref lemon::DfsVisit::addSource() "addSource()".
1359 1358
    /// Finally \ref lemon::DfsVisit::start() "start()" will perform the
1360 1359
    /// actual path computation.
1361 1360

	
1362 1361
    /// @{
1363 1362

	
1364 1363
    /// \brief Initializes the internal data structures.
1365 1364
    ///
1366 1365
    /// Initializes the internal data structures.
1367 1366
    void init() {
1368 1367
      create_maps();
1369 1368
      _stack.resize(countNodes(*_digraph));
1370 1369
      _stack_head = -1;
1371 1370
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1372 1371
        _reached->set(u, false);
1373 1372
      }
1374 1373
    }
1375 1374

	
1376 1375
    ///Adds a new source node.
1377 1376

	
1378 1377
    ///Adds a new source node to the set of nodes to be processed.
1379 1378
    ///
1380 1379
    ///\pre The stack must be empty. (Otherwise the algorithm gives
1381 1380
    ///false results.)
1382 1381
    ///
1383 1382
    ///\warning Distances will be wrong (or at least strange) in case of
1384 1383
    ///multiple sources.
1385 1384
    void addSource(Node s)
1386 1385
    {
1387 1386
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
1388 1387
      if(!(*_reached)[s]) {
1389 1388
          _reached->set(s,true);
1390 1389
          _visitor->start(s);
1391 1390
          _visitor->reach(s);
1392 1391
          Arc e;
1393 1392
          _digraph->firstOut(e, s);
1394 1393
          if (e != INVALID) {
1395 1394
            _stack[++_stack_head] = e;
1396 1395
          } else {
1397 1396
            _visitor->leave(s);
1398 1397
          }
1399 1398
        }
1400 1399
    }
1401 1400

	
1402 1401
    /// \brief Processes the next arc.
1403 1402
    ///
1404 1403
    /// Processes the next arc.
1405 1404
    ///
1406 1405
    /// \return The processed arc.
1407 1406
    ///
1408 1407
    /// \pre The stack must not be empty.
1409 1408
    Arc processNextArc() {
1410 1409
      Arc e = _stack[_stack_head];
1411 1410
      Node m = _digraph->target(e);
1412 1411
      if(!(*_reached)[m]) {
1413 1412
        _visitor->discover(e);
1414 1413
        _visitor->reach(m);
1415 1414
        _reached->set(m, true);
1416 1415
        _digraph->firstOut(_stack[++_stack_head], m);
1417 1416
      } else {
1418 1417
        _visitor->examine(e);
1419 1418
        m = _digraph->source(e);
1420 1419
        _digraph->nextOut(_stack[_stack_head]);
1421 1420
      }
1422 1421
      while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1423 1422
        _visitor->leave(m);
1424 1423
        --_stack_head;
1425 1424
        if (_stack_head >= 0) {
1426 1425
          _visitor->backtrack(_stack[_stack_head]);
1427 1426
          m = _digraph->source(_stack[_stack_head]);
1428 1427
          _digraph->nextOut(_stack[_stack_head]);
1429 1428
        } else {
1430 1429
          _visitor->stop(m);
1431 1430
        }
1432 1431
      }
1433 1432
      return e;
1434 1433
    }
1435 1434

	
1436 1435
    /// \brief Next arc to be processed.
1437 1436
    ///
1438 1437
    /// Next arc to be processed.
1439 1438
    ///
1440 1439
    /// \return The next arc to be processed or INVALID if the stack is
1441 1440
    /// empty.
1442 1441
    Arc nextArc() const {
1443 1442
      return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1444 1443
    }
1445 1444

	
1446 1445
    /// \brief Returns \c false if there are nodes
1447 1446
    /// to be processed.
1448 1447
    ///
1449 1448
    /// Returns \c false if there are nodes
1450 1449
    /// to be processed in the queue (stack).
1451 1450
    bool emptyQueue() const { return _stack_head < 0; }
1452 1451

	
1453 1452
    /// \brief Returns the number of the nodes to be processed.
1454 1453
    ///
1455 1454
    /// Returns the number of the nodes to be processed in the queue (stack).
1456 1455
    int queueSize() const { return _stack_head + 1; }
1457 1456

	
1458 1457
    /// \brief Executes the algorithm.
1459 1458
    ///
1460 1459
    /// Executes the algorithm.
1461 1460
    ///
1462 1461
    /// This method runs the %DFS algorithm from the root node
1463 1462
    /// in order to compute the %DFS path to each node.
1464 1463
    ///
1465 1464
    /// The algorithm computes
1466 1465
    /// - the %DFS tree,
1467 1466
    /// - the distance of each node from the root in the %DFS tree.
1468 1467
    ///
1469 1468
    /// \pre init() must be called and a root node should be
1470 1469
    /// added with addSource() before using this function.
1471 1470
    ///
1472 1471
    /// \note <tt>d.start()</tt> is just a shortcut of the following code.
1473 1472
    /// \code
1474 1473
    ///   while ( !d.emptyQueue() ) {
1475 1474
    ///     d.processNextArc();
1476 1475
    ///   }
1477 1476
    /// \endcode
1478 1477
    void start() {
1479 1478
      while ( !emptyQueue() ) processNextArc();
1480 1479
    }
1481 1480

	
1482 1481
    /// \brief Executes the algorithm until the given target node is reached.
1483 1482
    ///
1484 1483
    /// Executes the algorithm until the given target node is reached.
1485 1484
    ///
1486 1485
    /// This method runs the %DFS algorithm from the root node
1487 1486
    /// in order to compute the DFS path to \c dest.
1488 1487
    ///
1489 1488
    /// The algorithm computes
1490 1489
    /// - the %DFS path to \c dest,
1491 1490
    /// - the distance of \c dest from the root in the %DFS tree.
1492 1491
    ///
1493 1492
    /// \pre init() must be called and a root node should be added
1494 1493
    /// with addSource() before using this function.
1495 1494
    void start(Node dest) {
1496 1495
      while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != dest )
1497 1496
        processNextArc();
1498 1497
    }
1499 1498

	
1500 1499
    /// \brief Executes the algorithm until a condition is met.
1501 1500
    ///
1502 1501
    /// Executes the algorithm until a condition is met.
1503 1502
    ///
1504 1503
    /// This method runs the %DFS algorithm from the root node
1505 1504
    /// until an arc \c a with <tt>am[a]</tt> true is found.
1506 1505
    ///
1507 1506
    /// \param am A \c bool (or convertible) arc map. The algorithm
1508 1507
    /// will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
1509 1508
    ///
1510 1509
    /// \return The reached arc \c a with <tt>am[a]</tt> true or
1511 1510
    /// \c INVALID if no such arc was found.
1512 1511
    ///
1513 1512
    /// \pre init() must be called and a root node should be added
1514 1513
    /// with addSource() before using this function.
1515 1514
    ///
1516 1515
    /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
1517 1516
    /// not a node map.
1518 1517
    template <typename AM>
1519 1518
    Arc start(const AM &am) {
1520 1519
      while ( !emptyQueue() && !am[_stack[_stack_head]] )
1521 1520
        processNextArc();
1522 1521
      return emptyQueue() ? INVALID : _stack[_stack_head];
1523 1522
    }
1524 1523

	
1525 1524
    /// \brief Runs the algorithm from the given node.
1526 1525
    ///
1527 1526
    /// This method runs the %DFS algorithm from node \c s.
1528 1527
    /// in order to compute the DFS path to each node.
1529 1528
    ///
1530 1529
    /// The algorithm computes
1531 1530
    /// - the %DFS tree,
1532 1531
    /// - the distance of each node from the root in the %DFS tree.
1533 1532
    ///
1534 1533
    /// \note <tt>d.run(s)</tt> is just a shortcut of the following code.
1535 1534
    ///\code
1536 1535
    ///   d.init();
1537 1536
    ///   d.addSource(s);
1538 1537
    ///   d.start();
1539 1538
    ///\endcode
1540 1539
    void run(Node s) {
1541 1540
      init();
1542 1541
      addSource(s);
1543 1542
      start();
1544 1543
    }
1545 1544

	
1546 1545
    /// \brief Finds the %DFS path between \c s and \c t.
1547 1546

	
1548 1547
    /// This method runs the %DFS algorithm from node \c s
1549 1548
    /// in order to compute the DFS path to \c t.
1550 1549
    ///
1551 1550
    /// \return The length of the <tt>s</tt>--<tt>t</tt> DFS path,
1552 1551
    /// if \c t is reachable form \c s, \c 0 otherwise.
1553 1552
    ///
1554 1553
    /// \note Apart from the return value, <tt>d.run(s,t)</tt> is
1555 1554
    /// just a shortcut of the following code.
1556 1555
    ///\code
1557 1556
    ///   d.init();
1558 1557
    ///   d.addSource(s);
1559 1558
    ///   d.start(t);
1560 1559
    ///\endcode
1561 1560
    int run(Node s,Node t) {
1562 1561
      init();
1563 1562
      addSource(s);
1564 1563
      start(t);
1565 1564
      return reached(t)?_stack_head+1:0;
1566 1565
    }
1567 1566

	
1568 1567
    /// \brief Runs the algorithm to visit all nodes in the digraph.
1569 1568

	
1570 1569
    /// This method runs the %DFS algorithm in order to
1571 1570
    /// compute the %DFS path to each node.
1572 1571
    ///
1573 1572
    /// The algorithm computes
1574 1573
    /// - the %DFS tree,
1575 1574
    /// - the distance of each node from the root in the %DFS tree.
1576 1575
    ///
1577 1576
    /// \note <tt>d.run()</tt> is just a shortcut of the following code.
1578 1577
    ///\code
1579 1578
    ///   d.init();
1580 1579
    ///   for (NodeIt n(digraph); n != INVALID; ++n) {
1581 1580
    ///     if (!d.reached(n)) {
1582 1581
    ///       d.addSource(n);
1583 1582
    ///       d.start();
1584 1583
    ///     }
1585 1584
    ///   }
1586 1585
    ///\endcode
1587 1586
    void run() {
1588 1587
      init();
1589 1588
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1590 1589
        if (!reached(it)) {
1591 1590
          addSource(it);
1592 1591
          start();
1593 1592
        }
1594 1593
      }
1595 1594
    }
1596 1595

	
1597 1596
    ///@}
1598 1597

	
1599 1598
    /// \name Query Functions
1600 1599
    /// The result of the %DFS algorithm can be obtained using these
1601 1600
    /// functions.\n
1602 1601
    /// Either \ref lemon::DfsVisit::run() "run()" or
1603 1602
    /// \ref lemon::DfsVisit::start() "start()" must be called before
1604 1603
    /// using them.
1605 1604
    ///@{
1606 1605

	
1607 1606
    /// \brief Checks if a node is reachable from the root(s).
1608 1607
    ///
1609 1608
    /// Returns \c true if \c v is reachable from the root(s).
1610 1609
    /// \pre Either \ref run() or \ref start()
1611 1610
    /// must be called before using this function.
1612 1611
    bool reached(Node v) { return (*_reached)[v]; }
1613 1612

	
1614 1613
    ///@}
1615 1614

	
1616 1615
  };
1617 1616

	
1618 1617
} //END OF NAMESPACE LEMON
1619 1618

	
1620 1619
#endif
Ignore white space 1073741824 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_DIJKSTRA_H
20 20
#define LEMON_DIJKSTRA_H
21 21

	
22 22
///\ingroup shortest_path
23 23
///\file
24 24
///\brief Dijkstra algorithm.
25 25

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

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default operation traits for the Dijkstra algorithm class.
37 37
  ///
38 38
  /// This operation traits class defines all computational operations and
39 39
  /// constants which are used in the Dijkstra algorithm.
40 40
  template <typename Value>
41 41
  struct DijkstraDefaultOperationTraits {
42 42
    /// \brief Gives back the zero value of the type.
43 43
    static Value zero() {
44 44
      return static_cast<Value>(0);
45 45
    }
46 46
    /// \brief Gives back the sum of the given two elements.
47 47
    static Value plus(const Value& left, const Value& right) {
48 48
      return left + right;
49 49
    }
50 50
    /// \brief Gives back true only if the first value is less than the second.
51 51
    static bool less(const Value& left, const Value& right) {
52 52
      return left < right;
53 53
    }
54 54
  };
55 55

	
56 56
  /// \brief Widest path operation traits for the Dijkstra algorithm class.
57 57
  ///
58 58
  /// This operation traits class defines all computational operations and
59 59
  /// constants which are used in the Dijkstra algorithm for widest path
60 60
  /// computation.
61 61
  ///
62 62
  /// \see DijkstraDefaultOperationTraits
63 63
  template <typename Value>
64 64
  struct DijkstraWidestPathOperationTraits {
65 65
    /// \brief Gives back the maximum value of the type.
66 66
    static Value zero() {
67 67
      return std::numeric_limits<Value>::max();
68 68
    }
69 69
    /// \brief Gives back the minimum of the given two elements.
70 70
    static Value plus(const Value& left, const Value& right) {
71 71
      return std::min(left, right);
72 72
    }
73 73
    /// \brief Gives back true only if the first value is less than the second.
74 74
    static bool less(const Value& left, const Value& right) {
75 75
      return left < right;
76 76
    }
77 77
  };
78 78

	
79 79
  ///Default traits class of Dijkstra class.
80 80

	
81 81
  ///Default traits class of Dijkstra class.
82 82
  ///\tparam GR The type of the digraph.
83 83
  ///\tparam LM The type of the length map.
84 84
  template<class GR, class LM>
85 85
  struct DijkstraDefaultTraits
86 86
  {
87 87
    ///The type of the digraph the algorithm runs on.
88 88
    typedef GR Digraph;
89 89

	
90 90
    ///The type of the map that stores the arc lengths.
91 91

	
92 92
    ///The type of the map that stores the arc lengths.
93 93
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
94 94
    typedef LM LengthMap;
95 95
    ///The type of the length of the arcs.
96 96
    typedef typename LM::Value Value;
97 97

	
98 98
    /// Operation traits for Dijkstra algorithm.
99 99

	
100 100
    /// This class defines the operations that are used in the algorithm.
101 101
    /// \see DijkstraDefaultOperationTraits
102 102
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
103 103

	
104 104
    /// The cross reference type used by the heap.
105 105

	
106 106
    /// The cross reference type used by the heap.
107 107
    /// Usually it is \c Digraph::NodeMap<int>.
108 108
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
109 109
    ///Instantiates a \ref HeapCrossRef.
110 110

	
111 111
    ///This function instantiates a \ref HeapCrossRef.
112 112
    /// \param g is the digraph, to which we would like to define the
113 113
    /// \ref HeapCrossRef.
114 114
    static HeapCrossRef *createHeapCrossRef(const Digraph &g)
115 115
    {
116 116
      return new HeapCrossRef(g);
117 117
    }
118 118

	
119 119
    ///The heap type used by the Dijkstra algorithm.
120 120

	
121 121
    ///The heap type used by the Dijkstra algorithm.
122 122
    ///
123 123
    ///\sa BinHeap
124 124
    ///\sa Dijkstra
125 125
    typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap;
126 126
    ///Instantiates a \ref Heap.
127 127

	
128 128
    ///This function instantiates a \ref Heap.
129 129
    static Heap *createHeap(HeapCrossRef& r)
130 130
    {
131 131
      return new Heap(r);
132 132
    }
133 133

	
134 134
    ///\brief The type of the map that stores the predecessor
135 135
    ///arcs of the shortest paths.
136 136
    ///
137 137
    ///The type of the map that stores the predecessor
138 138
    ///arcs of the shortest paths.
139 139
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
140 140
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
141 141
    ///Instantiates a \ref PredMap.
142 142

	
143 143
    ///This function instantiates a \ref PredMap.
144 144
    ///\param g is the digraph, to which we would like to define the
145 145
    ///\ref PredMap.
146 146
    ///\todo The digraph alone may be insufficient for the initialization
147 147
    static PredMap *createPredMap(const Digraph &g)
148 148
    {
149 149
      return new PredMap(g);
150 150
    }
151 151

	
152 152
    ///The type of the map that indicates which nodes are processed.
153 153

	
154 154
    ///The type of the map that indicates which nodes are processed.
155 155
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
156 156
    ///By default it is a NullMap.
157 157
    ///\todo If it is set to a real map,
158 158
    ///Dijkstra::processed() should read this.
159 159
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
160 160
    ///Instantiates a \ref ProcessedMap.
161 161

	
162 162
    ///This function instantiates a \ref ProcessedMap.
163 163
    ///\param g is the digraph, to which
164 164
    ///we would like to define the \ref ProcessedMap
165 165
#ifdef DOXYGEN
166 166
    static ProcessedMap *createProcessedMap(const Digraph &g)
167 167
#else
168 168
    static ProcessedMap *createProcessedMap(const Digraph &)
169 169
#endif
170 170
    {
171 171
      return new ProcessedMap();
172 172
    }
173 173

	
174 174
    ///The type of the map that stores the distances of the nodes.
175 175

	
176 176
    ///The type of the map that stores the distances of the nodes.
177 177
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
178 178
    typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
179 179
    ///Instantiates a \ref DistMap.
180 180

	
181 181
    ///This function instantiates a \ref DistMap.
182 182
    ///\param g is the digraph, to which we would like to define
183 183
    ///the \ref DistMap
184 184
    static DistMap *createDistMap(const Digraph &g)
185 185
    {
186 186
      return new DistMap(g);
187 187
    }
188 188
  };
189 189

	
190 190
  ///%Dijkstra algorithm class.
191 191

	
192 192
  /// \ingroup shortest_path
193 193
  ///This class provides an efficient implementation of the %Dijkstra algorithm.
194 194
  ///
195 195
  ///The arc lengths are passed to the algorithm using a
196 196
  ///\ref concepts::ReadMap "ReadMap",
197 197
  ///so it is easy to change it to any kind of length.
198 198
  ///The type of the length is determined by the
199 199
  ///\ref concepts::ReadMap::Value "Value" of the length map.
200 200
  ///It is also possible to change the underlying priority heap.
201 201
  ///
202 202
  ///There is also a \ref dijkstra() "function type interface" for the
203 203
  ///%Dijkstra algorithm, which is convenient in the simplier cases and
204 204
  ///it can be used easier.
205 205
  ///
206 206
  ///\tparam GR The type of the digraph the algorithm runs on.
207 207
  ///The default value is \ref ListDigraph.
208 208
  ///The value of GR is not used directly by \ref Dijkstra, it is only
209 209
  ///passed to \ref DijkstraDefaultTraits.
210 210
  ///\tparam LM A readable arc map that determines the lengths of the
211 211
  ///arcs. It is read once for each arc, so the map may involve in
212 212
  ///relatively time consuming process to compute the arc lengths if
213 213
  ///it is necessary. The default map type is \ref
214 214
  ///concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
215 215
  ///The value of LM is not used directly by \ref Dijkstra, it is only
216 216
  ///passed to \ref DijkstraDefaultTraits.
217 217
  ///\tparam TR Traits class to set various data types used by the algorithm.
218 218
  ///The default traits class is \ref DijkstraDefaultTraits
219 219
  ///"DijkstraDefaultTraits<GR,LM>". See \ref DijkstraDefaultTraits
220 220
  ///for the documentation of a Dijkstra traits class.
221 221
#ifdef DOXYGEN
222 222
  template <typename GR, typename LM, typename TR>
223 223
#else
224 224
  template <typename GR=ListDigraph,
225 225
            typename LM=typename GR::template ArcMap<int>,
226 226
            typename TR=DijkstraDefaultTraits<GR,LM> >
227 227
#endif
228 228
  class Dijkstra {
229 229
  public:
230 230
    ///\ref Exception for uninitialized parameters.
231 231

	
232 232
    ///This error represents problems in the initialization of the
233 233
    ///parameters of the algorithm.
234 234
    class UninitializedParameter : public lemon::UninitializedParameter {
235 235
    public:
236 236
      virtual const char* what() const throw() {
237 237
        return "lemon::Dijkstra::UninitializedParameter";
238 238
      }
239 239
    };
240 240

	
241 241
    ///The type of the digraph the algorithm runs on.
242 242
    typedef typename TR::Digraph Digraph;
243 243

	
244 244
    ///The type of the length of the arcs.
245 245
    typedef typename TR::LengthMap::Value Value;
246 246
    ///The type of the map that stores the arc lengths.
247 247
    typedef typename TR::LengthMap LengthMap;
248 248
    ///\brief The type of the map that stores the predecessor arcs of the
249 249
    ///shortest paths.
250 250
    typedef typename TR::PredMap PredMap;
251 251
    ///The type of the map that stores the distances of the nodes.
252 252
    typedef typename TR::DistMap DistMap;
253 253
    ///The type of the map that indicates which nodes are processed.
254 254
    typedef typename TR::ProcessedMap ProcessedMap;
255 255
    ///The type of the paths.
256 256
    typedef PredMapPath<Digraph, PredMap> Path;
257 257
    ///The cross reference type used for the current heap.
258 258
    typedef typename TR::HeapCrossRef HeapCrossRef;
259 259
    ///The heap type used by the algorithm.
260 260
    typedef typename TR::Heap Heap;
261 261
    ///The operation traits class.
262 262
    typedef typename TR::OperationTraits OperationTraits;
263 263

	
264 264
    ///The traits class.
265 265
    typedef TR Traits;
266 266

	
267 267
  private:
268 268

	
269 269
    typedef typename Digraph::Node Node;
270 270
    typedef typename Digraph::NodeIt NodeIt;
271 271
    typedef typename Digraph::Arc Arc;
272 272
    typedef typename Digraph::OutArcIt OutArcIt;
273 273

	
274 274
    //Pointer to the underlying digraph.
275 275
    const Digraph *G;
276 276
    //Pointer to the length map.
277 277
    const LengthMap *length;
278 278
    //Pointer to the map of predecessors arcs.
279 279
    PredMap *_pred;
280 280
    //Indicates if _pred is locally allocated (true) or not.
281 281
    bool local_pred;
282 282
    //Pointer to the map of distances.
283 283
    DistMap *_dist;
284 284
    //Indicates if _dist is locally allocated (true) or not.
285 285
    bool local_dist;
286 286
    //Pointer to the map of processed status of the nodes.
287 287
    ProcessedMap *_processed;
288 288
    //Indicates if _processed is locally allocated (true) or not.
289 289
    bool local_processed;
290 290
    //Pointer to the heap cross references.
291 291
    HeapCrossRef *_heap_cross_ref;
292 292
    //Indicates if _heap_cross_ref is locally allocated (true) or not.
293 293
    bool local_heap_cross_ref;
294 294
    //Pointer to the heap.
295 295
    Heap *_heap;
296 296
    //Indicates if _heap is locally allocated (true) or not.
297 297
    bool local_heap;
298 298

	
299 299
    ///Creates the maps if necessary.
300 300
    ///\todo Better memory allocation (instead of new).
301 301
    void create_maps()
302 302
    {
303 303
      if(!_pred) {
304 304
        local_pred = true;
305 305
        _pred = Traits::createPredMap(*G);
306 306
      }
307 307
      if(!_dist) {
308 308
        local_dist = true;
309 309
        _dist = Traits::createDistMap(*G);
310 310
      }
311 311
      if(!_processed) {
312 312
        local_processed = true;
313 313
        _processed = Traits::createProcessedMap(*G);
314 314
      }
315 315
      if (!_heap_cross_ref) {
316 316
        local_heap_cross_ref = true;
317 317
        _heap_cross_ref = Traits::createHeapCrossRef(*G);
318 318
      }
319 319
      if (!_heap) {
320 320
        local_heap = true;
321 321
        _heap = Traits::createHeap(*_heap_cross_ref);
322 322
      }
323 323
    }
324 324

	
325 325
  public:
326 326

	
327 327
    typedef Dijkstra Create;
328 328

	
329 329
    ///\name Named template parameters
330 330

	
331 331
    ///@{
332 332

	
333 333
    template <class T>
334
    struct DefPredMapTraits : public Traits {
334
    struct SetPredMapTraits : public Traits {
335 335
      typedef T PredMap;
336 336
      static PredMap *createPredMap(const Digraph &)
337 337
      {
338 338
        throw UninitializedParameter();
339 339
      }
340 340
    };
341 341
    ///\brief \ref named-templ-param "Named parameter" for setting
342 342
    ///\ref PredMap type.
343 343
    ///
344 344
    ///\ref named-templ-param "Named parameter" for setting
345 345
    ///\ref PredMap type.
346 346
    template <class T>
347
    struct DefPredMap
348
      : public Dijkstra< Digraph, LengthMap, DefPredMapTraits<T> > {
349
      typedef Dijkstra< Digraph, LengthMap, DefPredMapTraits<T> > Create;
347
    struct SetPredMap
348
      : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
349
      typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
350 350
    };
351 351

	
352 352
    template <class T>
353
    struct DefDistMapTraits : public Traits {
353
    struct SetDistMapTraits : public Traits {
354 354
      typedef T DistMap;
355 355
      static DistMap *createDistMap(const Digraph &)
356 356
      {
357 357
        throw UninitializedParameter();
358 358
      }
359 359
    };
360 360
    ///\brief \ref named-templ-param "Named parameter" for setting
361 361
    ///\ref DistMap type.
362 362
    ///
363 363
    ///\ref named-templ-param "Named parameter" for setting
364 364
    ///\ref DistMap type.
365 365
    template <class T>
366
    struct DefDistMap
367
      : public Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > {
368
      typedef Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > Create;
366
    struct SetDistMap
367
      : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
368
      typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
369 369
    };
370 370

	
371 371
    template <class T>
372
    struct DefProcessedMapTraits : public Traits {
372
    struct SetProcessedMapTraits : public Traits {
373 373
      typedef T ProcessedMap;
374 374
      static ProcessedMap *createProcessedMap(const Digraph &)
375 375
      {
376 376
        throw UninitializedParameter();
377 377
      }
378 378
    };
379 379
    ///\brief \ref named-templ-param "Named parameter" for setting
380 380
    ///\ref ProcessedMap type.
381 381
    ///
382 382
    ///\ref named-templ-param "Named parameter" for setting
383 383
    ///\ref ProcessedMap type.
384 384
    template <class T>
385
    struct DefProcessedMap
386
      : public Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > {
387
      typedef Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > Create;
385
    struct SetProcessedMap
386
      : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
387
      typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
388 388
    };
389 389

	
390
    struct DefDigraphProcessedMapTraits : public Traits {
390
    struct SetStandardProcessedMapTraits : public Traits {
391 391
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
392 392
      static ProcessedMap *createProcessedMap(const Digraph &g)
393 393
      {
394 394
        return new ProcessedMap(g);
395 395
      }
396 396
    };
397 397
    ///\brief \ref named-templ-param "Named parameter" for setting
398 398
    ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
399 399
    ///
400 400
    ///\ref named-templ-param "Named parameter" for setting
401 401
    ///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
402 402
    ///If you don't set it explicitly, it will be automatically allocated.
403
    template <class T>
404
    struct DefProcessedMapToBeDefaultMap
405
      : public Dijkstra< Digraph, LengthMap, DefDigraphProcessedMapTraits> {
406
      typedef Dijkstra< Digraph, LengthMap, DefDigraphProcessedMapTraits>
403
    struct SetStandardProcessedMap
404
      : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
405
      typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
407 406
      Create;
408 407
    };
409 408

	
410 409
    template <class H, class CR>
411
    struct DefHeapTraits : public Traits {
410
    struct SetHeapTraits : public Traits {
412 411
      typedef CR HeapCrossRef;
413 412
      typedef H Heap;
414 413
      static HeapCrossRef *createHeapCrossRef(const Digraph &) {
415 414
        throw UninitializedParameter();
416 415
      }
417 416
      static Heap *createHeap(HeapCrossRef &)
418 417
      {
419 418
        throw UninitializedParameter();
420 419
      }
421 420
    };
422 421
    ///\brief \ref named-templ-param "Named parameter" for setting
423 422
    ///heap and cross reference type
424 423
    ///
425 424
    ///\ref named-templ-param "Named parameter" for setting heap and cross
426 425
    ///reference type.
427 426
    template <class H, class CR = typename Digraph::template NodeMap<int> >
428
    struct DefHeap
429
      : public Dijkstra< Digraph, LengthMap, DefHeapTraits<H, CR> > {
430
      typedef Dijkstra< Digraph, LengthMap, DefHeapTraits<H, CR> > Create;
427
    struct SetHeap
428
      : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
429
      typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
431 430
    };
432 431

	
433 432
    template <class H, class CR>
434
    struct DefStandardHeapTraits : public Traits {
433
    struct SetStandardHeapTraits : public Traits {
435 434
      typedef CR HeapCrossRef;
436 435
      typedef H Heap;
437 436
      static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
438 437
        return new HeapCrossRef(G);
439 438
      }
440 439
      static Heap *createHeap(HeapCrossRef &R)
441 440
      {
442 441
        return new Heap(R);
443 442
      }
444 443
    };
445 444
    ///\brief \ref named-templ-param "Named parameter" for setting
446 445
    ///heap and cross reference type with automatic allocation
447 446
    ///
448 447
    ///\ref named-templ-param "Named parameter" for setting heap and cross
449 448
    ///reference type. It can allocate the heap and the cross reference
450 449
    ///object if the cross reference's constructor waits for the digraph as
451 450
    ///parameter and the heap's constructor waits for the cross reference.
452 451
    template <class H, class CR = typename Digraph::template NodeMap<int> >
453
    struct DefStandardHeap
454
      : public Dijkstra< Digraph, LengthMap, DefStandardHeapTraits<H, CR> > {
455
      typedef Dijkstra< Digraph, LengthMap, DefStandardHeapTraits<H, CR> >
452
    struct SetStandardHeap
453
      : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
454
      typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
456 455
      Create;
457 456
    };
458 457

	
459 458
    template <class T>
460
    struct DefOperationTraitsTraits : public Traits {
459
    struct SetOperationTraitsTraits : public Traits {
461 460
      typedef T OperationTraits;
462 461
    };
463 462

	
464 463
    /// \brief \ref named-templ-param "Named parameter" for setting
465 464
    ///\ref OperationTraits type
466 465
    ///
467 466
    ///\ref named-templ-param "Named parameter" for setting
468 467
    ///\ref OperationTraits type.
469 468
    template <class T>
470
    struct DefOperationTraits
471
      : public Dijkstra<Digraph, LengthMap, DefOperationTraitsTraits<T> > {
472
      typedef Dijkstra<Digraph, LengthMap, DefOperationTraitsTraits<T> >
469
    struct SetOperationTraits
470
      : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
471
      typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
473 472
      Create;
474 473
    };
475 474

	
476 475
    ///@}
477 476

	
478 477
  protected:
479 478

	
480 479
    Dijkstra() {}
481 480

	
482 481
  public:
483 482

	
484 483
    ///Constructor.
485 484

	
486 485
    ///Constructor.
487 486
    ///\param _g The digraph the algorithm runs on.
488 487
    ///\param _length The length map used by the algorithm.
489 488
    Dijkstra(const Digraph& _g, const LengthMap& _length) :
490 489
      G(&_g), length(&_length),
491 490
      _pred(NULL), local_pred(false),
492 491
      _dist(NULL), local_dist(false),
493 492
      _processed(NULL), local_processed(false),
494 493
      _heap_cross_ref(NULL), local_heap_cross_ref(false),
495 494
      _heap(NULL), local_heap(false)
496 495
    { }
497 496

	
498 497
    ///Destructor.
499 498
    ~Dijkstra()
500 499
    {
501 500
      if(local_pred) delete _pred;
502 501
      if(local_dist) delete _dist;
503 502
      if(local_processed) delete _processed;
504 503
      if(local_heap_cross_ref) delete _heap_cross_ref;
505 504
      if(local_heap) delete _heap;
506 505
    }
507 506

	
508 507
    ///Sets the length map.
509 508

	
510 509
    ///Sets the length map.
511 510
    ///\return <tt> (*this) </tt>
512 511
    Dijkstra &lengthMap(const LengthMap &m)
513 512
    {
514 513
      length = &m;
515 514
      return *this;
516 515
    }
517 516

	
518 517
    ///Sets the map that stores the predecessor arcs.
519 518

	
520 519
    ///Sets the map that stores the predecessor arcs.
521 520
    ///If you don't use this function before calling \ref run(),
522 521
    ///it will allocate one. The destructor deallocates this
523 522
    ///automatically allocated map, of course.
524 523
    ///\return <tt> (*this) </tt>
525 524
    Dijkstra &predMap(PredMap &m)
526 525
    {
527 526
      if(local_pred) {
528 527
        delete _pred;
529 528
        local_pred=false;
530 529
      }
531 530
      _pred = &m;
532 531
      return *this;
533 532
    }
534 533

	
535 534
    ///Sets the map that indicates which nodes are processed.
536 535

	
537 536
    ///Sets the map that indicates which nodes are processed.
538 537
    ///If you don't use this function before calling \ref run(),
539 538
    ///it will allocate one. The destructor deallocates this
540 539
    ///automatically allocated map, of course.
541 540
    ///\return <tt> (*this) </tt>
542 541
    Dijkstra &processedMap(ProcessedMap &m)
543 542
    {
544 543
      if(local_processed) {
545 544
        delete _processed;
546 545
        local_processed=false;
547 546
      }
548 547
      _processed = &m;
549 548
      return *this;
550 549
    }
551 550

	
552 551
    ///Sets the map that stores the distances of the nodes.
553 552

	
554 553
    ///Sets the map that stores the distances of the nodes calculated by the
555 554
    ///algorithm.
556 555
    ///If you don't use this function before calling \ref run(),
557 556
    ///it will allocate one. The destructor deallocates this
558 557
    ///automatically allocated map, of course.
559 558
    ///\return <tt> (*this) </tt>
560 559
    Dijkstra &distMap(DistMap &m)
561 560
    {
562 561
      if(local_dist) {
563 562
        delete _dist;
564 563
        local_dist=false;
565 564
      }
566 565
      _dist = &m;
567 566
      return *this;
568 567
    }
569 568

	
570 569
    ///Sets the heap and the cross reference used by algorithm.
571 570

	
572 571
    ///Sets the heap and the cross reference used by algorithm.
573 572
    ///If you don't use this function before calling \ref run(),
574 573
    ///it will allocate one. The destructor deallocates this
575 574
    ///automatically allocated heap and cross reference, of course.
576 575
    ///\return <tt> (*this) </tt>
577 576
    Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
578 577
    {
579 578
      if(local_heap_cross_ref) {
580 579
        delete _heap_cross_ref;
581 580
        local_heap_cross_ref=false;
582 581
      }
583 582
      _heap_cross_ref = &cr;
584 583
      if(local_heap) {
585 584
        delete _heap;
586 585
        local_heap=false;
587 586
      }
588 587
      _heap = &hp;
589 588
      return *this;
590 589
    }
591 590

	
592 591
  private:
593 592

	
594 593
    void finalizeNodeData(Node v,Value dst)
595 594
    {
596 595
      _processed->set(v,true);
597 596
      _dist->set(v, dst);
598 597
    }
599 598

	
600 599
  public:
601 600

	
602 601
    ///\name Execution control
603 602
    ///The simplest way to execute the algorithm is to use one of the
604 603
    ///member functions called \ref lemon::Dijkstra::run() "run()".
605 604
    ///\n
606 605
    ///If you need more control on the execution, first you must call
607 606
    ///\ref lemon::Dijkstra::init() "init()", then you can add several
608 607
    ///source nodes with \ref lemon::Dijkstra::addSource() "addSource()".
609 608
    ///Finally \ref lemon::Dijkstra::start() "start()" will perform the
610 609
    ///actual path computation.
611 610

	
612 611
    ///@{
613 612

	
614 613
    ///Initializes the internal data structures.
615 614

	
616 615
    ///Initializes the internal data structures.
617 616
    ///
618 617
    void init()
619 618
    {
620 619
      create_maps();
621 620
      _heap->clear();
622 621
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
623 622
        _pred->set(u,INVALID);
624 623
        _processed->set(u,false);
625 624
        _heap_cross_ref->set(u,Heap::PRE_HEAP);
626 625
      }
627 626
    }
628 627

	
629 628
    ///Adds a new source node.
630 629

	
631 630
    ///Adds a new source node to the priority heap.
632 631
    ///The optional second parameter is the initial distance of the node.
633 632
    ///
634 633
    ///The function checks if the node has already been added to the heap and
635 634
    ///it is pushed to the heap only if either it was not in the heap
636 635
    ///or the shortest path found till then is shorter than \c dst.
637 636
    void addSource(Node s,Value dst=OperationTraits::zero())
638 637
    {
639 638
      if(_heap->state(s) != Heap::IN_HEAP) {
640 639
        _heap->push(s,dst);
641 640
      } else if(OperationTraits::less((*_heap)[s], dst)) {
642 641
        _heap->set(s,dst);
643 642
        _pred->set(s,INVALID);
644 643
      }
645 644
    }
646 645

	
647 646
    ///Processes the next node in the priority heap
648 647

	
649 648
    ///Processes the next node in the priority heap.
650 649
    ///
651 650
    ///\return The processed node.
652 651
    ///
653 652
    ///\warning The priority heap must not be empty.
654 653
    Node processNextNode()
655 654
    {
656 655
      Node v=_heap->top();
657 656
      Value oldvalue=_heap->prio();
658 657
      _heap->pop();
659 658
      finalizeNodeData(v,oldvalue);
660 659

	
661 660
      for(OutArcIt e(*G,v); e!=INVALID; ++e) {
662 661
        Node w=G->target(e);
663 662
        switch(_heap->state(w)) {
664 663
        case Heap::PRE_HEAP:
665 664
          _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e]));
666 665
          _pred->set(w,e);
667 666
          break;
668 667
        case Heap::IN_HEAP:
669 668
          {
670 669
            Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]);
671 670
            if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
672 671
              _heap->decrease(w, newvalue);
673 672
              _pred->set(w,e);
674 673
            }
675 674
          }
676 675
          break;
677 676
        case Heap::POST_HEAP:
678 677
          break;
679 678
        }
680 679
      }
681 680
      return v;
682 681
    }
683 682

	
684 683
    ///The next node to be processed.
685 684

	
686 685
    ///Returns the next node to be processed or \c INVALID if the
687 686
    ///priority heap is empty.
688 687
    Node nextNode() const
689 688
    {
690 689
      return !_heap->empty()?_heap->top():INVALID;
691 690
    }
692 691

	
693 692
    ///\brief Returns \c false if there are nodes
694 693
    ///to be processed.
695 694
    ///
696 695
    ///Returns \c false if there are nodes
697 696
    ///to be processed in the priority heap.
698 697
    bool emptyQueue() const { return _heap->empty(); }
699 698

	
700 699
    ///Returns the number of the nodes to be processed in the priority heap
701 700

	
702 701
    ///Returns the number of the nodes to be processed in the priority heap.
703 702
    ///
704 703
    int queueSize() const { return _heap->size(); }
705 704

	
706 705
    ///Executes the algorithm.
707 706

	
708 707
    ///Executes the algorithm.
709 708
    ///
710 709
    ///This method runs the %Dijkstra algorithm from the root node(s)
711 710
    ///in order to compute the shortest path to each node.
712 711
    ///
713 712
    ///The algorithm computes
714 713
    ///- the shortest path tree (forest),
715 714
    ///- the distance of each node from the root(s).
716 715
    ///
717 716
    ///\pre init() must be called and at least one root node should be
718 717
    ///added with addSource() before using this function.
719 718
    ///
720 719
    ///\note <tt>d.start()</tt> is just a shortcut of the following code.
721 720
    ///\code
722 721
    ///  while ( !d.emptyQueue() ) {
723 722
    ///    d.processNextNode();
724 723
    ///  }
725 724
    ///\endcode
726 725
    void start()
727 726
    {
728 727
      while ( !emptyQueue() ) processNextNode();
729 728
    }
730 729

	
731 730
    ///Executes the algorithm until the given target node is reached.
732 731

	
733 732
    ///Executes the algorithm until the given target node is reached.
734 733
    ///
735 734
    ///This method runs the %Dijkstra algorithm from the root node(s)
736 735
    ///in order to compute the shortest path to \c dest.
737 736
    ///
738 737
    ///The algorithm computes
739 738
    ///- the shortest path to \c dest,
740 739
    ///- the distance of \c dest from the root(s).
741 740
    ///
742 741
    ///\pre init() must be called and at least one root node should be
743 742
    ///added with addSource() before using this function.
744 743
    void start(Node dest)
745 744
    {
746 745
      while ( !_heap->empty() && _heap->top()!=dest ) processNextNode();
747 746
      if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio());
748 747
    }
749 748

	
750 749
    ///Executes the algorithm until a condition is met.
751 750

	
752 751
    ///Executes the algorithm until a condition is met.
753 752
    ///
754 753
    ///This method runs the %Dijkstra algorithm from the root node(s) in
755 754
    ///order to compute the shortest path to a node \c v with
756 755
    /// <tt>nm[v]</tt> true, if such a node can be found.
757 756
    ///
758 757
    ///\param nm A \c bool (or convertible) node map. The algorithm
759 758
    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
760 759
    ///
761 760
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
762 761
    ///\c INVALID if no such node was found.
763 762
    ///
764 763
    ///\pre init() must be called and at least one root node should be
765 764
    ///added with addSource() before using this function.
766 765
    template<class NodeBoolMap>
767 766
    Node start(const NodeBoolMap &nm)
768 767
    {
769 768
      while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
770 769
      if ( _heap->empty() ) return INVALID;
771 770
      finalizeNodeData(_heap->top(),_heap->prio());
772 771
      return _heap->top();
773 772
    }
774 773

	
775 774
    ///Runs the algorithm from the given node.
776 775

	
777 776
    ///This method runs the %Dijkstra algorithm from node \c s
778 777
    ///in order to compute the shortest path to each node.
779 778
    ///
780 779
    ///The algorithm computes
781 780
    ///- the shortest path tree,
782 781
    ///- the distance of each node from the root.
783 782
    ///
784 783
    ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
785 784
    ///\code
786 785
    ///  d.init();
787 786
    ///  d.addSource(s);
788 787
    ///  d.start();
789 788
    ///\endcode
790 789
    void run(Node s) {
791 790
      init();
792 791
      addSource(s);
793 792
      start();
794 793
    }
795 794

	
796 795
    ///Finds the shortest path between \c s and \c t.
797 796

	
798 797
    ///This method runs the %Dijkstra algorithm from node \c s
799 798
    ///in order to compute the shortest path to \c t.
800 799
    ///
801 800
    ///\return The length of the shortest <tt>s</tt>--<tt>t</tt> path,
802 801
    ///if \c t is reachable form \c s, \c 0 otherwise.
803 802
    ///
804 803
    ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
805 804
    ///shortcut of the following code.
806 805
    ///\code
807 806
    ///  d.init();
808 807
    ///  d.addSource(s);
809 808
    ///  d.start(t);
810 809
    ///\endcode
811 810
    Value run(Node s,Node t) {
812 811
      init();
813 812
      addSource(s);
814 813
      start(t);
815 814
      return (*_pred)[t]==INVALID?OperationTraits::zero():(*_dist)[t];
816 815
    }
817 816

	
818 817
    ///@}
819 818

	
820 819
    ///\name Query Functions
821 820
    ///The result of the %Dijkstra algorithm can be obtained using these
822 821
    ///functions.\n
823 822
    ///Either \ref lemon::Dijkstra::run() "run()" or
824 823
    ///\ref lemon::Dijkstra::start() "start()" must be called before
825 824
    ///using them.
826 825

	
827 826
    ///@{
828 827

	
829 828
    ///The shortest path to a node.
830 829

	
831 830
    ///Returns the shortest path to a node.
832 831
    ///
833 832
    ///\warning \c t should be reachable from the root(s).
834 833
    ///
835 834
    ///\pre Either \ref run() or \ref start() must be called before
836 835
    ///using this function.
837 836
    Path path(Node t) const { return Path(*G, *_pred, t); }
838 837

	
839 838
    ///The distance of a node from the root(s).
840 839

	
841 840
    ///Returns the distance of a node from the root(s).
842 841
    ///
843 842
    ///\warning If node \c v is not reachable from the root(s), then
844 843
    ///the return value of this function is undefined.
845 844
    ///
846 845
    ///\pre Either \ref run() or \ref start() must be called before
847 846
    ///using this function.
848 847
    Value dist(Node v) const { return (*_dist)[v]; }
849 848

	
850 849
    ///Returns the 'previous arc' of the shortest path tree for a node.
851 850

	
852 851
    ///This function returns the 'previous arc' of the shortest path
853 852
    ///tree for the node \c v, i.e. it returns the last arc of a
854 853
    ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
855 854
    ///is not reachable from the root(s) or if \c v is a root.
856 855
    ///
857 856
    ///The shortest path tree used here is equal to the shortest path
858 857
    ///tree used in \ref predNode().
859 858
    ///
860 859
    ///\pre Either \ref run() or \ref start() must be called before
861 860
    ///using this function.
862 861
    Arc predArc(Node v) const { return (*_pred)[v]; }
863 862

	
864 863
    ///Returns the 'previous node' of the shortest path tree for a node.
865 864

	
866 865
    ///This function returns the 'previous node' of the shortest path
867 866
    ///tree for the node \c v, i.e. it returns the last but one node
868 867
    ///from a shortest path from the root(s) to \c v. It is \c INVALID
869 868
    ///if \c v is not reachable from the root(s) or if \c v is a root.
870 869
    ///
871 870
    ///The shortest path tree used here is equal to the shortest path
872 871
    ///tree used in \ref predArc().
873 872
    ///
874 873
    ///\pre Either \ref run() or \ref start() must be called before
875 874
    ///using this function.
876 875
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
877 876
                                  G->source((*_pred)[v]); }
878 877

	
879 878
    ///\brief Returns a const reference to the node map that stores the
880 879
    ///distances of the nodes.
881 880
    ///
882 881
    ///Returns a const reference to the node map that stores the distances
883 882
    ///of the nodes calculated by the algorithm.
884 883
    ///
885 884
    ///\pre Either \ref run() or \ref init()
886 885
    ///must be called before using this function.
887 886
    const DistMap &distMap() const { return *_dist;}
888 887

	
889 888
    ///\brief Returns a const reference to the node map that stores the
890 889
    ///predecessor arcs.
891 890
    ///
892 891
    ///Returns a const reference to the node map that stores the predecessor
893 892
    ///arcs, which form the shortest path tree.
894 893
    ///
895 894
    ///\pre Either \ref run() or \ref init()
896 895
    ///must be called before using this function.
897 896
    const PredMap &predMap() const { return *_pred;}
898 897

	
899 898
    ///Checks if a node is reachable from the root(s).
900 899

	
901 900
    ///Returns \c true if \c v is reachable from the root(s).
902 901
    ///\pre Either \ref run() or \ref start()
903 902
    ///must be called before using this function.
904 903
    bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
905 904
                                        Heap::PRE_HEAP; }
906 905

	
907 906
    ///Checks if a node is processed.
908 907

	
909 908
    ///Returns \c true if \c v is processed, i.e. the shortest
910 909
    ///path to \c v has already found.
911 910
    ///\pre Either \ref run() or \ref start()
912 911
    ///must be called before using this function.
913 912
    bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
914 913
                                          Heap::POST_HEAP; }
915 914

	
916 915
    ///The current distance of a node from the root(s).
917 916

	
918 917
    ///Returns the current distance of a node from the root(s).
919 918
    ///It may be decreased in the following processes.
920 919
    ///\pre \c v should be reached but not processed.
921 920
    Value currentDist(Node v) const { return (*_heap)[v]; }
922 921

	
923 922
    ///@}
924 923
  };
925 924

	
926 925

	
927 926
  ///Default traits class of dijkstra() function.
928 927

	
929 928
  ///Default traits class of dijkstra() function.
930 929
  ///\tparam GR The type of the digraph.
931 930
  ///\tparam LM The type of the length map.
932 931
  template<class GR, class LM>
933 932
  struct DijkstraWizardDefaultTraits
934 933
  {
935 934
    ///The type of the digraph the algorithm runs on.
936 935
    typedef GR Digraph;
937 936
    ///The type of the map that stores the arc lengths.
938 937

	
939 938
    ///The type of the map that stores the arc lengths.
940 939
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
941 940
    typedef LM LengthMap;
942 941
    ///The type of the length of the arcs.
943 942
    typedef typename LM::Value Value;
944 943

	
945 944
    /// Operation traits for Dijkstra algorithm.
946 945

	
947 946
    /// This class defines the operations that are used in the algorithm.
948 947
    /// \see DijkstraDefaultOperationTraits
949 948
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
950 949

	
951 950
    /// The cross reference type used by the heap.
952 951

	
953 952
    /// The cross reference type used by the heap.
954 953
    /// Usually it is \c Digraph::NodeMap<int>.
955 954
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
956 955
    ///Instantiates a \ref HeapCrossRef.
957 956

	
958 957
    ///This function instantiates a \ref HeapCrossRef.
959 958
    /// \param g is the digraph, to which we would like to define the
960 959
    /// HeapCrossRef.
961 960
    /// \todo The digraph alone may be insufficient for the initialization
962 961
    static HeapCrossRef *createHeapCrossRef(const Digraph &g)
963 962
    {
964 963
      return new HeapCrossRef(g);
965 964
    }
966 965

	
967 966
    ///The heap type used by the Dijkstra algorithm.
968 967

	
969 968
    ///The heap type used by the Dijkstra algorithm.
970 969
    ///
971 970
    ///\sa BinHeap
972 971
    ///\sa Dijkstra
973 972
    typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
974 973
                    std::less<Value> > Heap;
975 974

	
976 975
    ///Instantiates a \ref Heap.
977 976

	
978 977
    ///This function instantiates a \ref Heap.
979 978
    /// \param r is the HeapCrossRef which is used.
980 979
    static Heap *createHeap(HeapCrossRef& r)
981 980
    {
982 981
      return new Heap(r);
983 982
    }
984 983

	
985 984
    ///\brief The type of the map that stores the predecessor
986 985
    ///arcs of the shortest paths.
987 986
    ///
988 987
    ///The type of the map that stores the predecessor
989 988
    ///arcs of the shortest paths.
990 989
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
991 990
    typedef NullMap <typename Digraph::Node,typename Digraph::Arc> PredMap;
992 991
    ///Instantiates a \ref PredMap.
993 992

	
994 993
    ///This function instantiates a \ref PredMap.
995 994
    ///\param g is the digraph, to which we would like to define the
996 995
    ///\ref PredMap.
997 996
    ///\todo The digraph alone may be insufficient to initialize
998 997
#ifdef DOXYGEN
999 998
    static PredMap *createPredMap(const Digraph &g)
1000 999
#else
1001 1000
    static PredMap *createPredMap(const Digraph &)
1002 1001
#endif
1003 1002
    {
1004 1003
      return new PredMap();
1005 1004
    }
1006 1005

	
1007 1006
    ///The type of the map that indicates which nodes are processed.
1008 1007

	
1009 1008
    ///The type of the map that indicates which nodes are processed.
1010 1009
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1011 1010
    ///By default it is a NullMap.
1012 1011
    ///\todo If it is set to a real map,
1013 1012
    ///Dijkstra::processed() should read this.
1014 1013
    ///\todo named parameter to set this type, function to read and write.
1015 1014
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
1016 1015
    ///Instantiates a \ref ProcessedMap.
1017 1016

	
1018 1017
    ///This function instantiates a \ref ProcessedMap.
1019 1018
    ///\param g is the digraph, to which
1020 1019
    ///we would like to define the \ref ProcessedMap.
1021 1020
#ifdef DOXYGEN
1022 1021
    static ProcessedMap *createProcessedMap(const Digraph &g)
1023 1022
#else
1024 1023
    static ProcessedMap *createProcessedMap(const Digraph &)
1025 1024
#endif
1026 1025
    {
1027 1026
      return new ProcessedMap();
1028 1027
    }
1029 1028

	
1030 1029
    ///The type of the map that stores the distances of the nodes.
1031 1030

	
1032 1031
    ///The type of the map that stores the distances of the nodes.
1033 1032
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1034 1033
    typedef NullMap<typename Digraph::Node,Value> DistMap;
1035 1034
    ///Instantiates a \ref DistMap.
1036 1035

	
1037 1036
    ///This function instantiates a \ref DistMap.
1038 1037
    ///\param g is the digraph, to which we would like to define
1039 1038
    ///the \ref DistMap
1040 1039
#ifdef DOXYGEN
1041 1040
    static DistMap *createDistMap(const Digraph &g)
1042 1041
#else
1043 1042
    static DistMap *createDistMap(const Digraph &)
1044 1043
#endif
1045 1044
    {
1046 1045
      return new DistMap();
1047 1046
    }
1048 1047
  };
1049 1048

	
1050 1049
  /// Default traits class used by \ref DijkstraWizard
1051 1050

	
1052 1051
  /// To make it easier to use Dijkstra algorithm
1053 1052
  /// we have created a wizard class.
1054 1053
  /// This \ref DijkstraWizard class needs default traits,
1055 1054
  /// as well as the \ref Dijkstra class.
1056 1055
  /// The \ref DijkstraWizardBase is a class to be the default traits of the
1057 1056
  /// \ref DijkstraWizard class.
1058 1057
  /// \todo More named parameters are required...
1059 1058
  template<class GR,class LM>
1060 1059
  class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
1061 1060
  {
1062 1061
    typedef DijkstraWizardDefaultTraits<GR,LM> Base;
1063 1062
  protected:
1064 1063
    //The type of the nodes in the digraph.
1065 1064
    typedef typename Base::Digraph::Node Node;
1066 1065

	
1067 1066
    //Pointer to the digraph the algorithm runs on.
1068 1067
    void *_g;
1069 1068
    //Pointer to the length map
1070 1069
    void *_length;
1071 1070
    //Pointer to the map of predecessors arcs.
1072 1071
    void *_pred;
1073 1072
    //Pointer to the map of distances.
1074 1073
    void *_dist;
1075 1074
    //Pointer to the source node.
1076 1075
    Node _source;
1077 1076

	
1078 1077
  public:
1079 1078
    /// Constructor.
1080 1079

	
1081 1080
    /// This constructor does not require parameters, therefore it initiates
1082 1081
    /// all of the attributes to default values (0, INVALID).
1083 1082
    DijkstraWizardBase() : _g(0), _length(0), _pred(0),
1084 1083
                           _dist(0), _source(INVALID) {}
1085 1084

	
1086 1085
    /// Constructor.
1087 1086

	
1088 1087
    /// This constructor requires some parameters,
1089 1088
    /// listed in the parameters list.
1090 1089
    /// Others are initiated to 0.
1091 1090
    /// \param g The digraph the algorithm runs on.
1092 1091
    /// \param l The length map.
1093 1092
    /// \param s The source node.
1094 1093
    DijkstraWizardBase(const GR &g,const LM &l, Node s=INVALID) :
1095 1094
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1096 1095
      _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1097 1096
      _pred(0), _dist(0), _source(s) {}
1098 1097

	
1099 1098
  };
1100 1099

	
1101 1100
  /// Auxiliary class for the function type interface of Dijkstra algorithm.
1102 1101

	
1103 1102
  /// This auxiliary class is created to implement the function type
1104 1103
  /// interface of \ref Dijkstra algorithm. It uses the functions and features
1105 1104
  /// of the plain \ref Dijkstra, but it is much simpler to use it.
1106 1105
  /// It should only be used through the \ref dijkstra() function, which makes
1107 1106
  /// it easier to use the algorithm.
1108 1107
  ///
1109 1108
  /// Simplicity means that the way to change the types defined
1110 1109
  /// in the traits class is based on functions that returns the new class
1111 1110
  /// and not on templatable built-in classes.
1112 1111
  /// When using the plain \ref Dijkstra
1113 1112
  /// the new class with the modified type comes from
1114 1113
  /// the original class by using the ::
1115 1114
  /// operator. In the case of \ref DijkstraWizard only
1116 1115
  /// a function have to be called, and it will
1117 1116
  /// return the needed class.
1118 1117
  ///
1119 1118
  /// It does not have own \ref run() method. When its \ref run() method
1120 1119
  /// is called, it initiates a plain \ref Dijkstra object, and calls the
1121 1120
  /// \ref Dijkstra::run() method of it.
1122 1121
  template<class TR>
1123 1122
  class DijkstraWizard : public TR
1124 1123
  {
1125 1124
    typedef TR Base;
1126 1125

	
1127 1126
    ///The type of the digraph the algorithm runs on.
1128 1127
    typedef typename TR::Digraph Digraph;
1129 1128

	
1130 1129
    typedef typename Digraph::Node Node;
1131 1130
    typedef typename Digraph::NodeIt NodeIt;
1132 1131
    typedef typename Digraph::Arc Arc;
1133 1132
    typedef typename Digraph::OutArcIt OutArcIt;
1134 1133

	
1135 1134
    ///The type of the map that stores the arc lengths.
1136 1135
    typedef typename TR::LengthMap LengthMap;
1137 1136
    ///The type of the length of the arcs.
1138 1137
    typedef typename LengthMap::Value Value;
1139 1138
    ///\brief The type of the map that stores the predecessor
1140 1139
    ///arcs of the shortest paths.
1141 1140
    typedef typename TR::PredMap PredMap;
1142 1141
    ///The type of the map that stores the distances of the nodes.
1143 1142
    typedef typename TR::DistMap DistMap;
1144 1143
    ///The type of the map that indicates which nodes are processed.
1145 1144
    typedef typename TR::ProcessedMap ProcessedMap;
1146 1145
    ///The heap type used by the dijkstra algorithm.
1147 1146
    typedef typename TR::Heap Heap;
1148 1147

	
1149 1148
  public:
1150 1149

	
1151 1150
    /// Constructor.
1152 1151
    DijkstraWizard() : TR() {}
1153 1152

	
1154 1153
    /// Constructor that requires parameters.
1155 1154

	
1156 1155
    /// Constructor that requires parameters.
1157 1156
    /// These parameters will be the default values for the traits class.
1158 1157
    DijkstraWizard(const Digraph &g,const LengthMap &l, Node s=INVALID) :
1159 1158
      TR(g,l,s) {}
1160 1159

	
1161 1160
    ///Copy constructor
1162 1161
    DijkstraWizard(const TR &b) : TR(b) {}
1163 1162

	
1164 1163
    ~DijkstraWizard() {}
1165 1164

	
1166 1165
    ///Runs Dijkstra algorithm from a source node.
1167 1166

	
1168 1167
    ///Runs Dijkstra algorithm from a source node.
1169 1168
    ///The node can be given with the \ref source() function.
1170 1169
    void run()
1171 1170
    {
1172 1171
      if(Base::_source==INVALID) throw UninitializedParameter();
1173 1172
      Dijkstra<Digraph,LengthMap,TR>
1174 1173
        dij(*reinterpret_cast<const Digraph*>(Base::_g),
1175 1174
            *reinterpret_cast<const LengthMap*>(Base::_length));
1176 1175
      if(Base::_pred) dij.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1177 1176
      if(Base::_dist) dij.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1178 1177
      dij.run(Base::_source);
1179 1178
    }
1180 1179

	
1181 1180
    ///Runs Dijkstra algorithm from the given node.
1182 1181

	
1183 1182
    ///Runs Dijkstra algorithm from the given node.
1184 1183
    ///\param s is the given source.
1185 1184
    void run(Node s)
1186 1185
    {
1187 1186
      Base::_source=s;
1188 1187
      run();
1189 1188
    }
1190 1189

	
1191 1190
    /// Sets the source node, from which the Dijkstra algorithm runs.
1192 1191

	
1193 1192
    /// Sets the source node, from which the Dijkstra algorithm runs.
1194 1193
    /// \param s is the source node.
1195 1194
    DijkstraWizard<TR> &source(Node s)
1196 1195
    {
1197 1196
      Base::_source=s;
1198 1197
      return *this;
1199 1198
    }
1200 1199

	
1201 1200
    template<class T>
1202
    struct DefPredMapBase : public Base {
1201
    struct SetPredMapBase : public Base {
1203 1202
      typedef T PredMap;
1204 1203
      static PredMap *createPredMap(const Digraph &) { return 0; };
1205
      DefPredMapBase(const TR &b) : TR(b) {}
1204
      SetPredMapBase(const TR &b) : TR(b) {}
1206 1205
    };
1207 1206
    ///\brief \ref named-templ-param "Named parameter"
1208 1207
    ///for setting \ref PredMap object.
1209 1208
    ///
1210 1209
    ///\ref named-templ-param "Named parameter"
1211 1210
    ///for setting \ref PredMap object.
1212 1211
    template<class T>
1213
    DijkstraWizard<DefPredMapBase<T> > predMap(const T &t)
1212
    DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1214 1213
    {
1215 1214
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1216
      return DijkstraWizard<DefPredMapBase<T> >(*this);
1215
      return DijkstraWizard<SetPredMapBase<T> >(*this);
1217 1216
    }
1218 1217

	
1219 1218
    template<class T>
1220
    struct DefProcessedMapBase : public Base {
1219
    struct SetProcessedMapBase : public Base {
1221 1220
      typedef T ProcessedMap;
1222 1221
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1223
      DefProcessedMapBase(const TR &b) : TR(b) {}
1222
      SetProcessedMapBase(const TR &b) : TR(b) {}
1224 1223
    };
1225 1224
    ///\brief \ref named-templ-param "Named parameter"
1226 1225
    ///for setting \ref ProcessedMap object.
1227 1226
    ///
1228 1227
    /// \ref named-templ-param "Named parameter"
1229 1228
    ///for setting \ref ProcessedMap object.
1230 1229
    template<class T>
1231
    DijkstraWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1230
    DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1232 1231
    {
1233 1232
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1234
      return DijkstraWizard<DefProcessedMapBase<T> >(*this);
1233
      return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1235 1234
    }
1236 1235

	
1237 1236
    template<class T>
1238
    struct DefDistMapBase : public Base {
1237
    struct SetDistMapBase : public Base {
1239 1238
      typedef T DistMap;
1240 1239
      static DistMap *createDistMap(const Digraph &) { return 0; };
1241
      DefDistMapBase(const TR &b) : TR(b) {}
1240
      SetDistMapBase(const TR &b) : TR(b) {}
1242 1241
    };
1243 1242
    ///\brief \ref named-templ-param "Named parameter"
1244 1243
    ///for setting \ref DistMap object.
1245 1244
    ///
1246 1245
    ///\ref named-templ-param "Named parameter"
1247 1246
    ///for setting \ref DistMap object.
1248 1247
    template<class T>
1249
    DijkstraWizard<DefDistMapBase<T> > distMap(const T &t)
1248
    DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1250 1249
    {
1251 1250
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1252
      return DijkstraWizard<DefDistMapBase<T> >(*this);
1251
      return DijkstraWizard<SetDistMapBase<T> >(*this);
1253 1252
    }
1254 1253

	
1255 1254
  };
1256 1255

	
1257 1256
  ///Function type interface for Dijkstra algorithm.
1258 1257

	
1259 1258
  /// \ingroup shortest_path
1260 1259
  ///Function type interface for Dijkstra algorithm.
1261 1260
  ///
1262 1261
  ///This function also has several
1263 1262
  ///\ref named-templ-func-param "named parameters",
1264 1263
  ///they are declared as the members of class \ref DijkstraWizard.
1265 1264
  ///The following
1266 1265
  ///example shows how to use these parameters.
1267 1266
  ///\code
1268 1267
  ///  dijkstra(g,length,source).predMap(preds).run();
1269 1268
  ///\endcode
1270 1269
  ///\warning Don't forget to put the \ref DijkstraWizard::run() "run()"
1271 1270
  ///to the end of the parameter list.
1272 1271
  ///\sa DijkstraWizard
1273 1272
  ///\sa Dijkstra
1274 1273
  template<class GR, class LM>
1275 1274
  DijkstraWizard<DijkstraWizardBase<GR,LM> >
1276 1275
  dijkstra(const GR &g,const LM &l,typename GR::Node s=INVALID)
1277 1276
  {
1278 1277
    return DijkstraWizard<DijkstraWizardBase<GR,LM> >(g,l,s);
1279 1278
  }
1280 1279

	
1281 1280
} //END OF NAMESPACE LEMON
1282 1281

	
1283 1282
#endif
Ignore white space 6 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
#include <iostream>
20 20
#include <fstream>
21 21
#include <string>
22 22
#include <vector>
23 23

	
24 24
#include <lemon/concept_check.h>
25 25
#include <lemon/concepts/heap.h>
26 26

	
27 27
#include <lemon/smart_graph.h>
28 28

	
29 29
#include <lemon/lgf_reader.h>
30 30
#include <lemon/dijkstra.h>
31 31
#include <lemon/maps.h>
32 32

	
33 33
#include <lemon/bin_heap.h>
34 34

	
35 35
#include "test_tools.h"
36 36

	
37 37
using namespace lemon;
38 38
using namespace lemon::concepts;
39 39

	
40 40
typedef ListDigraph Digraph;
41 41
DIGRAPH_TYPEDEFS(Digraph);
42 42

	
43 43
char test_lgf[] =
44 44
  "@nodes\n"
45 45
  "label\n"
46 46
  "0\n"
47 47
  "1\n"
48 48
  "2\n"
49 49
  "3\n"
50 50
  "4\n"
51 51
  "5\n"
52 52
  "6\n"
53 53
  "7\n"
54 54
  "8\n"
55 55
  "9\n"
56 56
  "@arcs\n"
57 57
  "                label   capacity\n"
58 58
  "0       5       0       94\n"
59 59
  "3       9       1       11\n"
60 60
  "8       7       2       83\n"
61 61
  "1       2       3       94\n"
62 62
  "5       7       4       35\n"
63 63
  "7       4       5       84\n"
64 64
  "9       5       6       38\n"
65 65
  "0       4       7       96\n"
66 66
  "6       7       8       6\n"
67 67
  "3       1       9       27\n"
68 68
  "5       2       10      77\n"
69 69
  "5       6       11      69\n"
70 70
  "6       5       12      41\n"
71 71
  "4       6       13      70\n"
72 72
  "3       2       14      45\n"
73 73
  "7       9       15      93\n"
74 74
  "5       9       16      50\n"
75 75
  "9       0       17      94\n"
76 76
  "9       6       18      67\n"
77 77
  "0       9       19      86\n"
78 78
  "@attributes\n"
79 79
  "source 3\n";
80 80

	
81 81
int test_seq[] = { 2, 28, 19, 27, 33, 25, 13, 41, 10, 26,  1,  9,  4, 34};
82 82
int test_inc[] = {20, 28, 34, 16,  0, 46, 44,  0, 42, 32, 14,  8,  6, 37};
83 83

	
84 84
int test_len = sizeof(test_seq) / sizeof(test_seq[0]);
85 85

	
86 86
template <typename Heap>
87 87
void heapSortTest() {
88 88
  RangeMap<int> map(test_len, -1);
89 89

	
90 90
  Heap heap(map);
91 91

	
92 92
  std::vector<int> v(test_len);
93 93

	
94 94
  for (int i = 0; i < test_len; ++i) {
95 95
    v[i] = test_seq[i];
96 96
    heap.push(i, v[i]);
97 97
  }
98 98
  std::sort(v.begin(), v.end());
99 99
  for (int i = 0; i < test_len; ++i) {
100 100
    check(v[i] == heap.prio() ,"Wrong order in heap sort.");
101 101
    heap.pop();
102 102
  }
103 103
}
104 104

	
105 105
template <typename Heap>
106 106
void heapIncreaseTest() {
107 107
  RangeMap<int> map(test_len, -1);
108 108

	
109 109
  Heap heap(map);
110 110

	
111 111
  std::vector<int> v(test_len);
112 112

	
113 113
  for (int i = 0; i < test_len; ++i) {
114 114
    v[i] = test_seq[i];
115 115
    heap.push(i, v[i]);
116 116
  }
117 117
  for (int i = 0; i < test_len; ++i) {
118 118
    v[i] += test_inc[i];
119 119
    heap.increase(i, v[i]);
120 120
  }
121 121
  std::sort(v.begin(), v.end());
122 122
  for (int i = 0; i < test_len; ++i) {
123 123
    check(v[i] == heap.prio() ,"Wrong order in heap increase test.");
124 124
    heap.pop();
125 125
  }
126 126
}
127 127

	
128 128

	
129 129

	
130 130
template <typename Heap>
131 131
void dijkstraHeapTest(const Digraph& digraph, const IntArcMap& length,
132 132
                      Node source) {
133 133

	
134
  typename Dijkstra<Digraph, IntArcMap>::template DefStandardHeap<Heap>::
134
  typename Dijkstra<Digraph, IntArcMap>::template SetStandardHeap<Heap>::
135 135
    Create dijkstra(digraph, length);
136 136

	
137 137
  dijkstra.run(source);
138 138

	
139 139
  for(ArcIt a(digraph); a != INVALID; ++a) {
140 140
    Node s = digraph.source(a);
141 141
    Node t = digraph.target(a);
142 142
    if (dijkstra.reached(s)) {
143 143
      check( dijkstra.dist(t) - dijkstra.dist(s) <= length[a],
144 144
             "Error in a shortest path tree!");
145 145
    }
146 146
  }
147 147

	
148 148
  for(NodeIt n(digraph); n != INVALID; ++n) {
149 149
    if ( dijkstra.reached(n) && dijkstra.predArc(n) != INVALID ) {
150 150
      Arc a = dijkstra.predArc(n);
151 151
      Node s = digraph.source(a);
152 152
      check( dijkstra.dist(n) - dijkstra.dist(s) == length[a],
153 153
             "Error in a shortest path tree!");
154 154
    }
155 155
  }
156 156

	
157 157
}
158 158

	
159 159
int main() {
160 160

	
161 161
  typedef int Item;
162 162
  typedef int Prio;
163 163
  typedef RangeMap<int> ItemIntMap;
164 164

	
165 165
  Digraph digraph;
166 166
  IntArcMap length(digraph);
167 167
  Node source;
168 168

	
169 169
  std::istringstream input(test_lgf);
170 170
  digraphReader(input, digraph).
171 171
    arcMap("capacity", length).
172 172
    node("source", source).
173 173
    run();
174 174

	
175 175
  {
176 176
    typedef BinHeap<Prio, ItemIntMap> IntHeap;
177 177
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
178 178
    heapSortTest<IntHeap>();
179 179
    heapIncreaseTest<IntHeap>();
180 180

	
181 181
    typedef BinHeap<Prio, IntNodeMap > NodeHeap;
182 182
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
183 183
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
184 184
  }
185 185

	
186 186
  return 0;
187 187
}
0 comments (0 inline)