Location: LEMON/LEMON-official/lemon/bfs.h

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