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 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
|
package Graph::Base;
use strict;
local $^W = 1;
use vars qw(@ISA);
=head1 NAME
Graph::Base - graph base class
=head1 SYNOPSIS
use Graph::Directed;
use Graph::Undirected;
$d1 = new Graph;
$d2 = new Graph::Directed;
$u = new Graph::Undirected;
=head1 DESCRIPTION
You create new graphs by calling the C<new> constructors of classes
C<Graph>, C<Graph::Directed>, and C<Graph::Undirected>. The classes
C<Graph> and C<Graph::Directed> are identical. After creating the
graph you can modify and explore the graph with following methods.
=over 4
=cut
require Exporter;
@ISA = qw(Exporter);
=pod
=item new
$G = Graph->new(@V)
Returns a new graph $G with the optional vertices @V.
=cut
sub new {
my $class = shift;
my $G = { };
bless $G, $class;
$G->add_vertices(@_) if @_;
return $G;
}
=pod
=item add_vertices
$G = $G->add_vertices(@v)
Adds the vertices to the graph $G, returns the graph.
=cut
sub add_vertices {
my ($G, @v) = @_;
@{ $G->{ V } }{ @v } = @v;
return $G;
}
=pod
=item add_vertex
$G = $G->add_vertex($v)
Adds the vertex $v to the graph $G, returns the graph.
=cut
sub add_vertex {
my ($G, $v) = @_;
return $G->add_vertices($v);
}
=pod
=item vertices
@V = $G->vertices
In list context returns the vertices @V of the graph $G.
In scalar context returns the number of the vertices.
=cut
sub vertices {
my $G = shift;
my @V = exists $G->{ V } ? sort values %{ $G->{ V } } : ();
return @V;
}
=pod
=item has_vertices
$G->has_vertices(@v)
In list context returns a list which contains the vertex
of the vertices @v if the vertex exists in the graph $G
and undef if it doesn't. In scalar context returns the
number of the existing vertices.
=cut
sub has_vertices {
my $G = shift;
return wantarray ?
map { exists $G->{ V }->{ $_ } ? $_ : undef } @_ :
grep { exists $G->{ V }->{ $_ } } @_ ;
}
=pod
=item has_vertex
$b = $G->has_vertex($v)
Returns true if the vertex $v exists in
the graph $G and false if it doesn't.
=cut
sub has_vertex {
my ($G, $v) = @_;
return defined $v && exists $G->{ V } && exists $G->{ V }->{ $v };
}
=pod
=item vertex
$v = $G->has_vertex($v)
Returns the vertex $v if the vertex exists in the graph $G
or undef if it doesn't.
=cut
sub vertex {
my ($G, $v) = @_;
return defined $v && $G->{ V }->{ $v };
}
=pod
=item directed
$b = $G->directed($d)
Set the directedness of the graph $G to $d or return the
current directedness. Directedness defaults to true.
=cut
sub directed {
my ($G, $d) = @_;
if (defined $d) {
if ($d) {
my $o = $G->{ D }; # Old directedness.
$G->{ D } = $d;
if (not $o) {
my @E = $G->edges;
while (my ($u, $v) = splice(@E, 0, 2)) {
$G->add_edge($v, $u);
}
}
return bless $G, 'Graph::Directed'; # Re-bless.
} else {
return $G->undirected(not $d);
}
}
return $G->{ D };
}
=pod
=item undirected
$b = $G->undirected($d)
Set the undirectedness of the graph $G to $u or return the
current undirectedness. Undirectedness defaults to false.
=cut
sub undirected {
my ($G, $u) = @_;
$G->{ D } = 1 unless defined $G->{ D };
if (defined $u) {
if ($u) {
my $o = $G->{ D }; # Old directedness.
$G->{ D } = not $u;
if ($o) {
my @E = $G->edges;
my %E;
while (my ($u, $v) = splice(@E, 0, 2)) {
# Throw away duplicate edges.
$G->delete_edge($u, $v) if exists $E{$v}->{$u};
$E{$u}->{$v}++;
}
}
return bless $G, 'Graph::Undirected'; # Re-bless.
} else {
return $G->directed(not $u);
}
}
return not $G->{ D };
}
=pod
=item has_edge
$b = $G->has_edge($u, $v)
Return true if the graph $G has the edge between
the vertices $u, $v.
=cut
sub has_edge {
my ($G, $u, $v) = @_;
return exists $G->{ Succ }->{ $u }->{ $v } ||
($G->undirected && exists $G->{ Succ }->{ $v }->{ $u });
}
=pod
=item has_edges
$G->has_edges($u1, $v1, $u2, $v2, ...)
In list context returns a list which contains true for each
edge in the graph $G defined by the vertices $u1, $v1, ...,
and false for each non-existing edge. In scalar context
returns the number of the existing edges.
=cut
sub has_edges {
my $G = shift;
my @e;
while (my ($u, $v) = splice(@_, 0, 2)) {
push @e, $G->has_edge($u, $v);
}
return wantarray ? @e : grep { $_ } @e;
}
=pod
=item has_path
$G->has_path($u, $v, ...)
Return true if the graph $G has the cycle defined by
the vertices $u, $v, ..., false otherwise.
=cut
sub has_path {
my $G = shift;
my $u = shift;
while (my $v = shift) {
return 0 unless $G->has_edge($u, $v);
$u = $v;
}
return 1;
}
=pod
=item has_cycle
$G->has_cycle($u, $v, ...)
Return true if the graph $G has the cycle defined by
the vertices $u, $v, ...,false otherwise.
=cut
sub has_cycle {
my $G = shift;
return $G->has_path(@_, $_[0]); # Just wrap around.
}
# _union_vertex_set
#
# $G->_union_vertex_set($u, $v)
#
# (INTERNAL USE ONLY)
# Adds the vertices $u and $v in the graph $G to the same vertex set.
#
sub _union_vertex_set {
my ($G, $u, $v) = @_;
my $su = $G->vertex_set( $u );
my $sv = $G->vertex_set( $v );
return if $su eq $sv;
my $ru = $G->{ VertexSetRank }->{ $su };
my $rv = $G->{ VertexSetRank }->{ $sv };
if ( $ru < $rv ) { # Union by rank (weight balancing).
$G->{ VertexSetParent }->{ $su } = $sv;
} else {
$G->{ VertexSetParent }->{ $sv } = $su;
$G->{ VertexSetRank }->{ $sv }++ if $ru == $rv;
}
}
=pod
=item vertex_set
$s = $G->vertex_set($v)
Returns the vertex set of the vertex $v in the graph $G.
A "vertex set" is represented by its parent vertex.
=cut
sub vertex_set {
my ($G, $v) = @_;
if ( exists $G->{ VertexSetParent }->{ $v } ) {
# Path compression.
$G->{ VertexSetParent }->{ $v } =
$G->vertex_set( $G->{ VertexSetParent }->{ $v } )
if $v ne $G->{ VertexSetParent }->{ $v };
} else {
$G->{ VertexSetParent }->{ $v } = $v;
$G->{ VertexSetRank }->{ $v } = 0;
}
return $G->{ VertexSetParent }->{ $v };
}
=pod
=item add_edge
$G = $G->add_edge($u, $v)
Adds the edge defined by the vertices $u, $v, to the graph $G.
Also implicitly adds the vertices. Returns the graph.
=cut
sub add_edge {
my ($G, $u, $v) = @_;
$G->add_vertex($u);
$G->add_vertex($v);
$G->_union_vertex_set( $u, $v );
push @{ $G->{ Succ }->{ $u }->{ $v } }, $v;
push @{ $G->{ Pred }->{ $v }->{ $u } }, $u;
return $G;
}
=pod
=item add_edges
$G = $G->add_edges($u1, $v1, $u2, $v2, ...)
Adds the edge defined by the vertices $u1, $v1, ...,
to the graph $G. Also implicitly adds the vertices.
Returns the graph.
=cut
sub add_edges {
my $G = shift;
while (my ($u, $v) = splice(@_, 0, 2)) {
$G->add_edge($u, $v);
}
return $G;
}
=pod
=item add_path
$G->add_path($u, $v, ...)
Adds the path defined by the vertices $u, $v, ...,
to the graph $G. Also implicitly adds the vertices.
Returns the graph.
=cut
sub add_path {
my $G = shift;
my $u = shift;
while (my $v = shift) {
$G->add_edge($u, $v);
$u = $v;
}
return $G;
}
=pod
=item add_cycle
$G = $G->add_cycle($u, $v, ...)
Adds the cycle defined by the vertices $u, $v, ...,
to the graph $G. Also implicitly adds the vertices.
Returns the graph.
=cut
sub add_cycle {
my $G = shift;
$G->add_path(@_, $_[0]); # Just wrap around.
}
# _successors
#
# @s = $G->_successors($v)
#
# (INTERNAL USE ONLY, use only on directed graphs)
# Returns the successor vertices @s of the vertex
# in the graph $G.
#
sub _successors {
my ($G, $v) = @_;
my @s =
defined $G->{ Succ }->{ $v } ?
map { @{ $G->{ Succ }->{ $v }->{ $_ } } }
sort keys %{ $G->{ Succ }->{ $v } } :
( );
return @s;
}
# _predecessors
#
# @p = $G->_predecessors($v)
#
# (INTERNAL USE ONLY, use only on directed graphs)
# Returns the predecessor vertices @p of the vertex $v
# in the graph $G.
#
sub _predecessors {
my ($G, $v) = @_;
my @p =
defined $G->{ Pred }->{ $v } ?
map { @{ $G->{ Pred }->{ $v }->{ $_ } } }
sort keys %{ $G->{ Pred }->{ $v } } :
( );
return @p;
}
=pod
=item neighbors
@n = $G->neighbors($v)
Returns the neighbor vertices of the vertex in the graph.
(Also 'neighbours' works.)
=cut
sub neighbors {
my ($G, $v) = @_;
my @n = ($G->_successors($v), $G->_predecessors($v));
return @n;
}
use vars '*neighbours';
*neighbours = \&neighbors; # Keep both sides of the Atlantic happy.
=pod
=item successors
@s = $G->successors($v)
Returns the successor vertices of the vertex in the graph.
=cut
sub successors {
my ($G, $v) = @_;
return $G->directed ? $G->_successors($v) : $G->neighbors($v);
}
=pod
=item predecessors
@p = $G->predecessors($v)
Returns the predecessor vertices of the vertex in the graph.
=cut
sub predecessors {
my ($G, $v) = @_;
return $G->directed ? $G->_predecessors($v) : $G->neighbors($v);
}
=pod
=item out_edges
@e = $G->out_edges($v)
Returns the edges leading out of the vertex $v in the graph $G.
In list context returns the edges as ($start_vertex, $end_vertex)
pairs. In scalar context returns the number of the edges.
=cut
sub out_edges {
my ($G, $v) = @_;
return () unless $G->has_vertex($v);
my @e = $G->_edges($v, undef);
return wantarray ? @e : @e / 2;
}
=pod
=item in_edges
@e = $G->in_edges($v)
Returns the edges leading into the vertex $v in the graph $G.
In list context returns the edges as ($start_vertex, $end_vertex)
pairs; in scalar context returns the number of the edges.
=cut
sub in_edges {
my ($G, $v) = @_;
return () unless $G->has_vertex($v);
my @e = $G->_edges(undef, $v);
return wantarray ? @e : @e / 2;
}
=pod
=item edges
@e = $G->edges($u, $v)
Returns the edges between the vertices $u and $v, or if $v
is undefined, the edges leading into or out of the vertex $u,
or if $u is undefined, returns all the edges, of the graph $G.
In list context returns the edges as a list of
$start_vertex, $end_vertex pairs; in scalar context
returns the number of the edges.
=cut
sub edges {
my ($G, $u, $v) = @_;
return () if defined $v and not $G->has_vertex($v);
my @e =
defined $u ?
( defined $v ?
$G->_edges($u, $v) :
($G->in_edges($u), $G->out_edges($u)) ) :
$G->_edges;
return wantarray ? @e : @e / 2;
}
=pod
=item delete_edge
$G = $G->delete_edge($u, $v)
Deletes an edge defined by the vertices $u, $v from the graph $G.
Note that the edge need not actually exist.
Returns the graph.
=cut
sub delete_edge {
my ($G, $u, $v) = @_;
pop @{ $G->{ Succ }->{ $u }->{ $v } };
pop @{ $G->{ Pred }->{ $v }->{ $u } };
delete $G->{ Succ }->{ $u }->{ $v }
unless @{ $G->{ Succ }->{ $u }->{ $v } };
delete $G->{ Pred }->{ $v }->{ $u }
unless @{ $G->{ Pred }->{ $v }->{ $u } };
delete $G->{ Succ }->{ $u }
unless keys %{ $G->{ Succ }->{ $u } };
delete $G->{ Pred }->{ $v }
unless keys %{ $G->{ Pred }->{ $v } };
return $G;
}
=pod
=item delete_edges
$G = $G->delete_edges($u1, $v1, $u2, $v2, ..)
Deletes edges defined by the vertices $u1, $v1, ...,
from the graph $G.
Note that the edges need not actually exist.
Returns the graph.
=cut
sub delete_edges {
my $G = shift;
while (my ($u, $v) = splice(@_, 0, 2)) {
if (defined $v) {
$G->delete_edge($u, $v);
} else {
my @e = $G->edges($u);
while (($u, $v) = splice(@e, 0, 2)) {
$G->delete_edge($u, $v);
}
}
}
return $G;
}
=pod
=item delete_path
$G = $G->delete_path($u, $v, ...)
Deletes a path defined by the vertices $u, $v, ..., from the graph $G.
Note that the path need not actually exist. Returns the graph.
=cut
sub delete_path {
my $G = shift;
my $u = shift;
while (my $v = shift) {
$G->delete_edge($u, $v);
$u = $v;
}
return $G;
}
=pod
=item delete_cycle
$G = $G->delete_cycle($u, $v, ...)
Deletes a cycle defined by the vertices $u, $v, ..., from the graph $G.
Note that the cycle need not actually exist. Returns the graph.
=cut
sub delete_cycle {
my $G = shift;
$G->delete_path(@_, $_[0]); # Just wrap around.
}
=pod
=item delete_vertex
$G = $G->delete_vertex($v)
Deletes the vertex $v and all its edges from the graph $G.
Note that the vertex need not actually exist.
Returns the graph.
=cut
sub delete_vertex {
my ($G, $v) = @_;
$G->delete_edges($v);
delete $G->{ V }->{ $v };
return $G;
}
=pod
=item delete_vertices
$G = $G->delete_vertices(@v)
Deletes the vertices @v and all their edges from the graph $G.
Note that the vertices need not actually exist.
Returns the graph.
=cut
sub delete_vertices {
my $G = shift;
foreach my $v (@_) {
$G->delete_vertex($v);
}
return $G;
}
=pod
=item in_degree
$d = $G->in_degree($v)
Returns the in-degree of the vertex $v in the graph $G,
or, if $v is undefined, the total in-degree of all the
vertices of the graph, or undef if the vertex doesn't
exist in the graph.
=cut
sub in_degree {
my ($G, $v) = @_;
return undef unless $G->has_vertex($v);
if ($G->directed) {
if (defined $v) {
return scalar $G->in_edges($v);
} else {
my $in = 0;
foreach my $v ($G->vertices) {
$in += $G->in_degree($v);
}
return $in;
}
} else {
return scalar $G->edges($v);
}
}
=pod
=item out_degree
$d = $G->out_degree($v)
Returns the out-degree of the vertex $v in the graph $G,
or, if $v is undefined, the total out-degree of all the
vertices of the graph, of undef if the vertex doesn't
exist in the graph.
=cut
sub out_degree {
my ($G, $v) = @_;
return undef unless $G->has_vertex($v);
if ($G->directed) {
if (defined $v) {
return scalar $G->out_edges($v);
} else {
my $out = 0;
foreach my $v ($G->vertices) {
$out += $G->out_degree($v);
}
return $out;
}
} else {
return scalar $G->edges($v);
}
}
=pod
=item degree
$d = $G->degree($v)
Returns the degree of the vertex $v in the graph $G
or, if $v is undefined, the total degree of all the
vertices of the graph, or undef if the vertex $v
doesn't exist in the graph.
=cut
sub degree {
my ($G, $v) = @_;
if (defined $v) {
return undef unless $G->has_vertex($v);
if ($G->directed) {
return $G->in_degree($v) - $G->out_degree($v);
} else {
return $G->edges($v);
}
} else {
if ($G->directed) {
return 0;
} else {
my $deg = 0;
foreach my $v ($G->vertices) {
$deg += $G->degree($v);
}
return $deg;
}
}
}
=pod
=item average_degree
$d = $G->average_degree
Returns the average degree of the vertices of the graph $G.
=cut
sub average_degree {
my $G = shift;
my $V = $G->vertices;
return $V ? $G->degree / $V : 0;
}
=pod
=item is_source_vertex
$b = $G->is_source_vertex($v)
Returns true if the vertex $v is a source vertex of the graph $G.
=cut
sub is_source_vertex {
my ($G, $v) = @_;
$G->in_degree($v) == 0 && $G->out_degree($v) > 0;
}
=pod
=item is_sink_vertex
$b = $G->is_sink_vertex($v)
Returns true if the vertex $v is a sink vertex of the graph $G.
=cut
sub is_sink_vertex {
my ($G, $v) = @_;
$G->in_degree($v) > 0 && $G->out_degree($v) == 0;
}
=pod
=item is_isolated_vertex
$b = $G->is_isolated_vertex($v)
Returns true if the vertex $v is a isolated vertex of the graph $G.
=cut
sub is_isolated_vertex {
my ($G, $v) = @_;
$G->in_degree($v) == 0 && $G->out_degree($v) == 0;
}
=pod
=item is_exterior_vertex
$b = $G->is_exterior_vertex($v)
Returns true if the vertex $v is a exterior vertex of the graph $G.
=cut
sub is_exterior_vertex {
my ($G, $v) = @_;
$G->in_degree($v) == 0 xor $G->out_degree($v) == 0;
}
=pod
=item is_interior_vertex
$b = $G->is_interior_vertex($v)
Returns true if the vertex $v is a interior vertex of the graph $G.
=cut
sub is_interior_vertex {
my ($G, $v) = @_;
$G->in_degree($v) && $G->out_degree($v);
}
=pod
=item is_self_loop_vertex
$b = $G->is_self_loop_vertex($v)
Returns true if the vertex $v is a self-loop vertex of the graph $G.
=cut
sub is_self_loop_vertex {
my ($G, $v) = @_;
exists $G->{ Succ }->{ $v }->{ $v };
}
=pod
=item source_vertices
@s = $G->source_vertices
Returns the source vertices @s of the graph $G.
=cut
sub source_vertices {
my $G = shift;
return grep { $G->is_source_vertex($_) } $G->vertices;
}
=pod
=item sink_vertices
@s = $G->sink_vertices
Returns the sink vertices @s of the graph $G.
=cut
sub sink_vertices {
my $G = shift;
return grep { $G->is_sink_vertex($_) } $G->vertices;
}
=pod
=item isolated_vertices
@i = $G->isolated_vertices
Returns the isolated vertices @i of the graph $G.
=cut
sub isolated_vertices {
my $G = shift;
return grep { $G->is_isolated_vertex($_) } $G->vertices;
}
=pod
=item exterior_vertices
@e = $G->exterior_vertices
Returns the exterior vertices @e of the graph $G.
=cut
sub exterior_vertices {
my $G = shift;
return grep { $G->is_exterior_vertex($_) } $G->vertices;
}
=pod
=item interior_vertices
@i = $G->interior_vertices
Returns the interior vertices @i of the graph $G.
=cut
sub interior_vertices {
my $G = shift;
return grep { $G->is_interior_vertex($_) } $G->vertices;
}
=pod
=item self_loop_vertices
@s = $G->self_loop_vertices
Returns the self-loop vertices @s of the graph $G.
=cut
sub self_loop_vertices {
my $G = shift;
return grep { $G->is_self_loop_vertex($_) } $G->vertices;
}
=pod
=item density_limits
($sparse, $dense, $complete) = $G->density_limits
Returns the density limits for the number of edges
in the graph $G. Note that reaching $complete edges
does not really guarantee completeness because we
can have multigraphs. The limit of sparse is less
than 1/4 of the edges of the complete graph, the
limit of dense is more than 3/4 of the edges of the
complete graph.
=cut
sub density_limits {
my $G = shift;
my $V = $G->vertices;
my $M = $V * ($V - 1);
$M = $M / 2 if $G->undirected;
return ($M/4, 3*$M/4, $M);
}
=pod
=item density
$d = $G->density
Returns the density $d of the graph $G.
=cut
sub density {
my $G = shift;
my ($sparse, $dense, $complete) = $G->density_limits;
return $complete ? $G->edges / $complete : 0;
}
=pod
=item is_sparse
$d = $G->is_sparse
Returns true if the graph $G is sparse.
=cut
sub is_sparse {
my $G = shift;
my ($sparse, $dense, $complete) = $G->density_limits;
return $complete ? $G->edges / $complete <= $dense : 1;
}
=pod
=item is_dense
$d = $G->is_dense
Returns true if the graph $G is dense.
=cut
sub is_dense {
my $G = shift;
my ($sparse, $dense, $complete) = $G->density_limits;
return $complete ? $G->edges / $complete >= $dense : 0;
}
=pod
=item complete
$C = $G->complete;
Returns a new complete graph $C corresponding to the graph $G.
=cut
sub complete {
my $G = shift;
my $C = (ref $G)->new;
my @V = $G->vertices;
if ($G->directed) {
foreach my $u (@V) {
foreach my $v (@V) {
$C->add_edge($u, $v) unless $u eq $v;
}
}
} else {
my %E;
foreach my $u (@V) {
foreach my $v (@V) {
next if $u eq $v or $E{$u}->{$v} || $E{$v}->{$u};
$C->add_edge($u, $v);
$E{$u}->{$v}++;
$E{$v}->{$u}++;
}
}
}
$C->directed($G->directed);
return $C;
}
=pod
=item complement
$C = $G->complement;
Returns a new complement graph $C corresponding to the graph $G.
=cut
sub complement {
my $G = shift;
my $C = $G->complete;
if (my @E = $G->edges) {
while (my ($u, $v) = splice(@E, 0, 2)) {
$C->delete_edge($u, $v);
}
}
return $C;
}
=pod
=item copy
$C = $G->copy;
Returns a new graph $C corresponding to the graph $G.
=cut
sub copy {
my $G = shift;
my $C = (ref $G)->new($G->vertices);
if (my @E = $G->edges) {
while (my ($u, $v) = splice(@E, 0, 2)) {
$C->add_edge($u, $v);
}
}
$C->directed($G->directed);
return $C;
}
=pod
=item transpose
$T = $G->transpose;
Returns a new transpose graph $T corresponding to the graph $G.
=cut
sub transpose {
my $G = shift;
return $G->copy if $G->undirected;
my $T = (ref $G)->new($G->vertices);
if (my @E = $G->edges) {
while (my ($u, $v) = splice(@E, 0, 2)) {
$T->add_edge($v, $u);
}
}
return $T;
}
# _stringify
#
# $s = $G->_stringify($connector, $separator)
#
# (INTERNAL USE ONLY)
# Returns a string representation of the graph $G.
# The edges are represented by $connector and edges/isolated
# vertices are represented by $separator.
#
sub _stringify {
my ($G, $connector, $separator) = @_;
my @E = $G->edges;
my @e = map { [ $_ ] } $G->isolated_vertices;
while (my ($u, $v) = splice(@E, 0, 2)) {
push @e, [$u, $v];
}
return join($separator,
map { @$_ == 2 ?
join($connector, $_->[0], $_->[1]) :
$_->[0] }
sort { $a->[0] cmp $b->[0] || @$a <=> @$b } @e);
}
=pod
=item set_attribute
$G->set_attribute($attribute, $value)
$G->set_attribute($attribute, $v, $value)
$G->set_attribute($attribute, $u, $v, $value)
Sets the $attribute of graph/vertex/edge to $value
but only if the vertex/edge already exists. Returns
true if the attribute is set successfully, false if not.
=cut
sub set_attribute {
my $G = shift;
my $attribute = shift;
my $value = pop;
my ($u, $v) = @_;
if (defined $u) {
return 0 unless $G->has_vertex($u);
if (defined $v) {
return 0 unless $G->has_edge($u, $v);
$G->{ Attr }->{ E }->{ $u }->{ $v }->{ $attribute } = $value;
$G->{ Attr }->{ E }->{ $v }->{ $u }->{ $attribute } = $value
if $G->undirected;
} else {
$G->{ Attr }->{ V }->{ $u }->{ $attribute } = $value;
}
} else {
$G->{ Attr }->{ G }->{ $attribute } = $value;
}
return 1;
}
=pod
=item get_attribute
$value = $G->get_attribute($attribute)
$value = $G->get_attribute($attribute, $v)
$value = $G->get_attribute($attribute, $u, $v)
Returns the $value of $attribute of graph/vertex/edge.
=cut
sub get_attribute {
my $G = shift;
my $attribute = shift;
my ($u, $v) = @_;
if (defined $u) {
if (defined $v) {
return undef
unless exists $G->{ Attr }->{ E };
my $E = $G->{ Attr }->{ E };
if ( $G->directed ) {
return $E->{ $u }->{ $v }->{ $attribute };
} else {
return undef
unless exists $G->{ Attr }->{ E };
return $E->{ $u }->{ $v }->{ $attribute }
if exists $E->{ $u }->{ $v }->{ $attribute };
return $E->{ $v }->{ $u }->{ $attribute };
}
} else {
return $G->{ Attr }->{ V }->{ $u }->{ $attribute };
}
} else {
return $G->{ Attr }->{ G }->{ $attribute };
}
}
=pod
=item has_attribute
$value = $G->has_attribute($attribute)
$value = $G->has_attribute($attribute, $v)
$value = $G->has_attribute($attribute, $u, $v)
Returns the $value of $attribute of graph/vertex/edge.
=cut
sub has_attribute {
my $G = shift;
my $attribute = shift;
my ($u, $v) = @_;
if (defined $u) {
if (defined $v) {
return undef
unless exists $G->{ Attr }->{ E };
my $E = $G->{ Attr }->{ E };
if ( $G->directed ) {
return exists $E->{ $u }->{ $v }->{ $attribute };
} else {
return exists $E->{ $u }->{ $v }->{ $attribute } or
exists $E->{ $v }->{ $u }->{ $attribute };
}
} else {
exists $G->{ Attr }->{ V }->{ $u }->{ $attribute };
}
} else {
exists $G->{ Attr } &&
exists $G->{ Attr }->{ G }->{ $attribute };
}
}
=pod
=item get_attributes
%attributes = $G->get_attributes()
%attributes = $G->get_attributes($v)
%attributes = $G->get_attributes($u, $v)
Returns as a hash all the attribute names and values
of graph/vertex/edge.
=cut
sub get_attributes {
my $G = shift;
my ($u, $v) = @_;
return ( ) unless exists $G->{ Attr };
if (defined $u) {
if (defined $v) {
return exists $G->{ Attr }->{ E } &&
exists $G->{ Attr }->{ E }->{ $u } &&
exists $G->{ Attr }->{ E }->{ $u }->{ $v } ?
%{ $G->{ Attr }->{ E }->{ $u }->{ $v } } :
( );
} else {
return exists $G->{ Attr }->{ V } &&
exists $G->{ Attr }->{ V }->{ $u } ?
%{ $G->{ Attr }->{ V }->{ $u } } : ( );
}
} else {
return exists $G->{ Attr }->{ G } ?
%{ $G->{ Attr }->{ G } } : ( );
}
}
=pod
=item delete_attribute
$G->delete_attribute($attribute)
$G->delete_attribute($attribute, $v)
$G->delete_attribute($attribute, $u, $v)
Deletes the $attribute of graph/vertex/edge.
=cut
sub delete_attribute {
my $G = shift;
my $attribute = shift;
my ($u, $v) = @_;
if (defined $u) {
if (defined $v) {
return undef
unless exists $G->{ Attr }->{ E };
my $E = $G->{ Attr }->{ E };
if ( $G->directed ) {
delete $E->{ $u }->{ $v }->{ $attribute };
} else {
delete $E->{ $v }->{ $u }->{ $attribute };
delete $E->{ $v }->{ $u }->{ $attribute };
}
} else {
delete $G->{ Attr }->{ V }->{ $u }->{ $attribute };
}
} else {
delete $G->{ Attr }->{ G }->{ $attribute };
}
}
=pod
=item delete_attributes
$G->delete_attributes()
$G->delete_attributes($v)
$G->delete_attributes($u, $v)
Deletes all the attributes of graph/vertex/edge.
=cut
sub delete_attributes {
my $G = shift;
my ($u, $v) = @_;
if (defined $u) {
if (defined $v) {
delete $G->{ Attr }->{ E }->{ $u }->{ $v };
} else {
delete $G->{ Attr }->{ V }->{ $u };
}
} else {
delete $G->{ Attr }->{ G };
}
}
=pod
=item add_weighted_edge
$G->add_weighted_edge($u, $w, $v, $a)
Adds in the graph $G an edge from vertex $u to vertex $v
and the edge attribute 'weight' set to $w.
=cut
sub add_weighted_edge {
my ($G, $u, $w, $v, $a) = @_;
$G->add_edge($u, $v);
$G->set_attribute('weight', $u, $v, $w);
}
=pod
=item add_weighted_edges
$G->add_weighted_edges($u1, $w1, $v1, $u2, $w2, $v2, ...)
Adds in the graph $G the weighted edges.
=cut
sub add_weighted_edges {
my $G = shift;
while (my ($u, $w, $v) = splice(@_, 0, 3)) {
$G->add_weighted_edge($u, $w, $v);
}
}
=pod
=item add_weighted_path
$G->add_weighted_path($v1, $w1, $v2, $w2, ..., $wnm1, $vn)
Adds in the graph $G the n edges defined by the path $v1 ... $vn
with the n-1 'weight' attributes $w1 ... $wnm1
=cut
sub add_weighted_path {
my $G = shift;
my $u = shift;
while (my ($w, $v) = splice(@_, 0, 2)) {
$G->add_weighted_edge($u, $w, $v);
$u = $v;
}
}
=pod
=item MST_Kruskal
$MST = $G->MST_Kruskal;
Returns Kruskal's Minimum Spanning Tree (as a graph) of
the graph $G based on the 'weight' attributes of the edges.
(Needs the ->vertex_set() method.)
=cut
sub MST_Kruskal {
my $G = shift;
my $MST = (ref $G)->new;
my @E = $G->edges;
my (@W, $u, $v, $w);
while (($u, $v) = splice(@E, 0, 2)) {
$w = $G->get_attribute('weight', $u, $v);
next unless defined $w; # undef weight == infinitely heavy
push @W, [ $u, $v, $w ];
}
$MST->directed( $G->directed );
# Sort by weights.
foreach my $e ( sort { $a->[ 2 ] <=> $b->[ 2 ] } @W ) {
($u, $v, $w) = @$e;
$MST->add_weighted_edge( $u, $w, $v )
unless $MST->vertex_set( $u ) eq $MST->vertex_set( $v );
}
return $MST;
}
=pod
=item edge_classify
@C = $G->edge_classify(%param)
Returns the edge classification as a list where each element
is a triplet [$u, $v, $class] the $u, $v being the vertices
of an edge and $class being the class. The %param can be
used to control the search.
=cut
sub edge_classify {
my $G = shift;
my $unseen_successor =
sub {
my ($u, $v, $T) = @_;
# Freshly seen successors make for tree edges.
push @{ $T->{ edge_class_list } },
[ $u, $v, 'tree' ];
};
my $seen_successor =
sub {
my ($u, $v, $T) = @_;
my $class;
if ( $T->{ G }->directed ) {
$class = 'cross'; # Default for directed non-tree edges.
unless ( exists $T->{ vertex_finished }->{ $v } ) {
$class = 'back';
} elsif ( $T->{ vertex_found }->{ $u } <
$T->{ vertex_found }->{ $v }) {
$class = 'forward';
}
} else {
# No cross nor forward edges in
# an undirected graph, by definition.
$class = 'back';
}
push @{ $T->{ edge_class_list } }, [ $u, $v, $class ];
};
use Graph::DFS;
my $d =
Graph::DFS->
new( $G,
unseen_successor => $unseen_successor,
seen_successor => $seen_successor,
@_);
$d->preorder;
return @{ $d->{ edge_class_list } };
}
=pod
=item toposort
@toposort = $G->toposort
Returns the vertices of the graph $G sorted topologically.
=cut
sub toposort {
my $G = shift;
my $d = Graph::DFS->new($G);
reverse $d->postorder; # That's it.
}
# _strongly_connected
#
# $s = $G->_strongly_connected
#
# (INTERNAL USE ONLY)
# Returns a graph traversal object that can be used for
# strong connection computations.
#
sub _strongly_connected {
my $G = shift;
my $T = $G->transpose;
Graph::DFS->
new($T,
# Pick the potential roots in their DFS postorder.
strong_root_order => [ reverse Graph::DFS->new($G)->postorder ],
get_next_root =>
sub {
my ($T, %param) = @_;
while (my $root =
shift @{ $param{ strong_root_order } }) {
return $root if exists $T->{ pool }->{ $root };
}
}
);
}
=pod
=item strongly_connected_components
@S = $G->strongly_connected_components
Returns the strongly connected components @S of the graph $G
as a list of anonymous lists of vertices, each anonymous list
containing the vertices belonging to one strongly connected
component.
=cut
sub strongly_connected_components {
my $G = shift;
my $T = $G->_strongly_connected;
my %R = $T->_vertex_roots;
my @C;
# Clump together vertices having identical root vertices.
while (my ($v, $r) = each %R) { push @{ $C[ $r ] }, $v }
return @C;
}
=pod
=item strongly_connected_graph
$T = $G->strongly_connected_graph
Returns the strongly connected graph $T of the graph $G.
The names of the strongly connected components are
formed from their constituent vertices by concatenating
their names by '+'-characters: "a" and "b" --> "a+b".
=cut
sub strongly_connected_graph {
my $G = shift;
my $C = (ref $G)->new;
my $T = $G->_strongly_connected;
my %R = $T->_vertex_roots;
my @C; # We're not calling the strongly_connected_components()
# method because we will need also the %R.
# Create the strongly connected components.
while (my ($v, $r) = each %R) { push @{ $C[$r] }, $v }
foreach my $c (@C) { $c = join("+", @$c) }
$C->directed( $G->directed );
my @E = $G->edges;
# Copy the edges between strongly connected components.
my $edge_cnt = 0;
my %n;
while (my ($u, $v) = splice(@E, 0, 2)) {
if ($R{ $u } != $R{ $v }) {
$C->add_edge( $C[ $R{ $u } ], $C[ $R{ $v } ] );
$edge_cnt++;
} elsif ($edge_cnt == 0) {
$n{ $u } = '';
}
}
if ($edge_cnt == 0) {
$C->add_vertex(join("+", keys %n));
}
return $C;
}
=pod
=item APSP_Floyd_Warshall
$APSP = $G->APSP_Floyd_Warshall
Returns the All-pairs Shortest Paths graph of the graph $G
computed using the Floyd-Warshall algorithm and the attribute
'weight' on the edges.
The returned graph has an edge for each shortest path.
An edge has attributes "weight" and "path"; for the length of
the shortest path and for the path (an anonymous list) itself.
=cut
sub APSP_Floyd_Warshall {
my $G = shift;
my @V = $G->vertices;
my @E = $G->edges;
my (%V2I, @I2V);
my (@P, @W);
# Compute the vertex <-> index mappings.
@V2I{ @V } = 0..$#V;
@I2V[ 0..$#V ] = @V;
# Initialize the predecessor matrix @P and the weight matrix @W.
# (The graph is converted into adjacency-matrix representation.)
# (The matrix is a list of lists.)
foreach my $i ( 0..$#V ) { $W[ $i ][ $i ] = 0 }
while ( my ($u, $v) = splice(@E, 0, 2) ) {
my ( $ui, $vi ) = ( $V2I{ $u }, $V2I{ $v } );
$P[ $ui ][ $vi ] = $ui unless $ui == $vi;
$W[ $ui ][ $vi ] = $G->get_attribute( 'weight', $u, $v );
}
# Do the O(N**3) loop.
for ( my $k = 0; $k < @V; $k++ ) {
my (@nP, @nW); # new @P, new @W
for ( my $i = 0; $i < @V; $i++ ) {
for ( my $j = 0; $j < @V; $j++ ) {
my $w_ij = $W[ $i ][ $j ];
my $w_ik_kj = $W[ $i ][ $k ] + $W[ $k ][ $j ]
if defined $W[ $i ][ $k ] and
defined $W[ $k ][ $j ];
# Choose the minimum of w_ij and w_ik_kj.
if ( defined $w_ij ) {
if ( defined $w_ik_kj ) {
if ( $w_ij <= $w_ik_kj ) {
$nP[ $i ][ $j ] = $P[ $i ][ $j ];
$nW[ $i ][ $j ] = $w_ij;
} else {
$nP[ $i ][ $j ] = $P[ $k ][ $j ];
$nW[ $i ][ $j ] = $w_ik_kj;
}
} else {
$nP[ $i ][ $j ] = $P[ $i ][ $j ];
$nW[ $i ][ $j ] = $w_ij;
}
} elsif ( defined $w_ik_kj ) {
$nP[ $i ][ $j ] = $P[ $k ][ $j ];
$nW[ $i ][ $j ] = $w_ik_kj;
}
}
}
@P = @nP; @W = @nW; # Update the predecessors and weights.
}
# Now construct the APSP graph.
my $APSP = (ref $G)->new;
$APSP->directed( $G->directed ); # Copy the directedness.
# Convert the adjacency-matrix representation
# into a Graph (adjacency-list representation).
for ( my $i = 0; $i < @V; $i++ ) {
my $iv = $I2V[ $i ];
for ( my $j = 0; $j < @V; $j++ ) {
if ( $i == $j ) {
$APSP->add_weighted_edge( $iv, 0, $iv );
$APSP->set_attribute("path", $iv, $iv, [ $iv ]);
next;
}
next unless defined $W[ $i ][ $j ];
my $jv = $I2V[ $j ];
$APSP->add_weighted_edge( $iv, $W[ $i ][ $j ], $jv );
my @path = ( $jv );
if ( $P[ $i ][ $j ] != $i ) {
my $k = $P[ $i ][ $j ]; # Walk back the path.
while ( $k != $i ) {
push @path, $I2V[ $k ];
$k = $P[ $i ][ $k ]; # Keep walking.
}
}
$APSP->set_attribute( "path", $iv, $jv, [ $iv, reverse @path ] );
}
}
return $APSP;
}
=pod
=item TransitiveClosure_Floyd_Warshall
$TransitiveClosure = $G->TransitiveClosure_Floyd_Warshall
Returns the Transitive Closure graph of the graph $G computed
using the Floyd-Warshall algorithm.
The resulting graph has an edge between each *ordered* pair of
vertices in which the second vertex is reachable from the first.
=cut
sub TransitiveClosure_Floyd_Warshall {
my $G = shift;
my @V = $G->vertices;
my @E = $G->edges;
my (%V2I, @I2V);
my @C = ( '' ) x @V;
# Compute the vertex <-> index mappings.
@V2I{ @V } = 0..$#V;
@I2V[ 0..$#V ] = @V;
# Initialize the closure matrix @C.
# (The graph is converted into adjacency-matrix representation.)
# (The matrix is a bit matrix. Well, a list of bit vectors.)
foreach my $i ( 0..$#V ) { vec( $C[ $i ], $i, 1 ) = 1 }
while ( my ($u, $v) = splice(@E, 0, 2) ) {
vec( $C[ $V2I{ $u } ], $V2I{ $v }, 1 ) = 1
}
# Do the O(N**3) loop.
for ( my $k = 0; $k < @V; $k++ ) {
my @nC = ( '' ) x @V; # new @C
for ( my $i = 0; $i < @V; $i++ ) {
for ( my $j = 0; $j < @V; $j++ ) {
vec( $nC[ $i ], $j, 1 ) =
vec( $C[ $i ], $j, 1 ) |
vec( $C[ $i ], $k, 1 ) & vec( $C[ $k ], $j, 1 );
}
}
@C = @nC; # Update the closure.
}
# Now construct the TransitiveClosure graph.
my $TransitiveClosure = (ref $G)->new;
$TransitiveClosure->directed( $G->directed );
# Convert the (closure-)adjacency-matrix representation
# into a Graph (adjacency-list representation).
for ( my $i = 0; $i < @V; $i++ ) {
for ( my $j = 0; $j < @V; $j++ ) {
$TransitiveClosure->add_edge( $I2V[ $i ], $I2V[ $j ] )
if vec( $C[ $i ], $j, 1 );
}
}
return $TransitiveClosure;
}
=pod
=item articulation points
@A = $G->articulation_points(%param)
Returns the articulation points (vertices) @A of the graph $G.
The %param can be used to control the search.
=cut
sub articulation_points {
my $G = shift;
my $articulate =
sub {
my ( $u, $T ) = @_;
my $ap = $T->{ vertex_found }->{ $u };
my @S = @{ $T->{ active_list } }; # Current stack.
$T->{ articulation_point }->{ $u } = $ap
unless exists $T->{ articulation_point }->{ $u };
# Walk back the stack marking the active DFS branch
# (below $u) as belonging to the articulation point $ap.
for ( my $i = 1; $i < @S; $i++ ) {
my $v = $S[ -$i ];
last if $v eq $u;
$T->{ articulation_point }->{ $v } = $ap
if not exists $T->{ articulation_point }->{ $v } or
$ap < $T->{ articulation_point }->{ $v };
}
};
my $unseen_successor =
sub {
my ($u, $v, $T) = @_;
# We need to know the number of children for root vertices.
$T->{ articulation_children }->{ $u }++;
};
my $seen_successor =
sub {
my ($u, $v, $T) = @_;
# If the $v is still active, articulate it.
$articulate->( $v, $T ) if exists $T->{ active_pool }->{ $v };
};
my $d =
Graph::DFS->new($G,
articulate => $articulate,
unseen_successor => $unseen_successor,
seen_successor => $seen_successor,
);
$d->preorder;
# Now we need to find (the indices of) unique articulation points
# and map them back to vertices.
my (%ap, @vf);
foreach my $v ( $G->vertices ) {
$ap{ $d->{ articulation_point }->{ $v } } = $v;
$vf[ $d->{ vertex_found }->{ $v } ] = $v;
}
%ap = map { ( $vf[ $_ ], $_ ) } keys %ap;
# DFS tree roots are articulation points only
# iff they have more than one children.
foreach my $r ( $d->roots ) {
delete $ap{ $r } if $d->{ articulation_children }->{ $r } < 2;
}
keys %ap;
}
=pod
=item is_biconnected
$b = $G->is_biconnected
Returns true is the graph $G is biconnected
(has no articulation points), false otherwise.
=cut
sub is_biconnected {
my $G = shift;
return $G->articulation_points == 0;
}
=pod
=item largest_out_degree
$v = $G->largest_out_degree( @V )
Selects the vertex $v from the vertices @V having
the largest out degree in the graph $G.
=cut
sub largest_out_degree {
my $G = shift;
my $L = shift;
my $O = $G->out_degree($L);
for my $e (@_) {
my $o = $G->out_degree($e);
if ($o > $O) {
$L = $e;
$O = $o;
}
}
return $L;
}
# _heap_init
#
# $G->_heap_init($heap, $u, \%in_heap, \%weight, \%parent)
#
# (INTERNAL USE ONLY)
# Initializes the $heap with the vertex $u as the initial
# vertex, its weight being zero, and marking all vertices
# of the graph $G to be $in_heap,
#
sub _heap_init {
my ($G, $heap, $u, $in_heap, $W, $P) = @_;
use Graph::HeapElem;
foreach my $v ( $G->vertices ) {
my $e = Graph::HeapElem->new( $v, $W, $P );
$heap->add( $e );
$in_heap->{ $v } = $e;
}
$W->{ $u } = 0;
}
=pod
=item MST_Prim
$MST = $G->MST_Prim($u)
Returns Prim's Minimum Spanning Tree (as a graph) of
the graph $G based on the 'weight' attributes of the edges.
The optional start vertex is $u, if none is given, a hopefully
good one (a vertex with a large out degree) is chosen.
=cut
sub MST_Prim {
my ( $G, $u ) = @_;
my $MST = (ref $G)->new;
$u = $G->largest_out_degree( $G->vertices ) unless defined $u;
use Heap::Fibonacci;
my $heap = Heap::Fibonacci->new;
my ( %in_heap, %weight, %parent );
$G->_heap_init( $heap, $u, \%in_heap, \%weight, \%parent );
# Walk the edges at the current BFS front
# in the order of their increasing weight.
while ( defined $heap->minimum ) {
$u = $heap->extract_minimum;
delete $in_heap{ $u->vertex };
# Now extend the BFS front.
foreach my $v ( $G->successors( $u->vertex ) ) {
if ( defined( $v = $in_heap{ $v } ) ) {
my $nw = $G->get_attribute( 'weight',
$u->vertex, $v->vertex );
my $ow = $v->weight;
if ( not defined $ow or $nw < $ow ) {
$v->weight( $nw );
$v->parent( $u->vertex );
$heap->decrease_key( $v );
}
}
}
}
foreach my $v ( $G->vertices ) {
$MST->add_weighted_edge( $v, $weight{ $v }, $parent{ $v } )
if defined $parent{ $v };
}
return $MST;
}
# _SSSP_construct
#
# $SSSP = $G->_SSSP_construct( $s, $W, $P );
#
# (INTERNAL USE ONLY)
# Return the SSSP($s) graph of graph $G based on the computed
# anonymous hashes for weights and parents: $W and $P.
# The vertices of the graph will have two attributes: "weight",
# which tells the length of the shortest single-source path,
# and "path", which is an anymous list containing the path.
#
sub _SSSP_construct {
my ($G, $s, $W, $P ) = @_;
my $SSSP = (ref $G)->new;
foreach my $u ( $G->vertices ) {
$SSSP->add_vertex( $u );
$SSSP->set_attribute( "weight", $u, $W->{ $u } || 0 );
my @path = ( $u );
if ( defined $P->{ $u } ) {
$SSSP->add_edge($P->{ $u }, $u );
$SSSP->set_attribute( "weight", $P->{ $u }, $u, $G->get_attribute("weight",$P->{ $u }, $u) || 0 );
push @path, $P->{ $u };
if ( $P->{ $u } ne $s ) {
my $v = $P->{ $u };
while ( defined $v && exists $P->{ $v } && $v ne $s ) {
push @path, $P->{ $v };
$v = $P->{ $v };
}
}
}
$SSSP->set_attribute( "path", $u, [ reverse @path ] );
}
return $SSSP;
}
=pod
=item SSSP_Dijkstra
$SSSP = $G->SSSP_Dijkstra($s)
Returns the Single-source Shortest Paths (as a graph)
of the graph $G starting from the vertex $s using Dijktra's
SSSP algorithm.
=cut
sub SSSP_Dijkstra {
my ( $G, $s ) = @_;
use Heap::Fibonacci;
my $heap = Heap::Fibonacci->new;
my ( %in_heap, %weight, %parent );
# The other weights are by default undef (infinite).
$weight{ $s } = 0;
$G->_heap_init($heap, $s, \%in_heap, \%weight, \%parent );
# Walk the edges at the current BFS front
# in the order of their increasing weight.
while ( defined $heap->minimum ) {
my $u = $heap->extract_minimum;
delete $in_heap{ $u->vertex };
# Now extend the BFS front.
my $uw = $u->weight;
foreach my $v ( $G->successors( $u->vertex ) ) {
if ( defined( $v = $in_heap{ $v } ) ) {
my $ow = $v->weight;
my $nw =
$G->get_attribute( 'weight', $u->vertex, $v->vertex ) +
($uw || 0); # The || 0 helps for undefined $uw.
# Relax the edge $u - $v.
if ( not defined $ow or $ow > $nw ) {
$v->weight( $nw );
$v->parent( $u->vertex );
$heap->decrease_key( $v );
}
}
}
}
return $G->_SSSP_construct( $s, \%weight, \%parent );
}
=pod
=item SSSP_Bellman_Ford
$SSSP = $G->SSSP_Bellman_Ford($s)
Returns the Single-source Shortest Paths (as a graph)
of the graph $G starting from the vertex $s using Bellman-Ford
SSSP algorithm. If there are one or more negatively weighted
cycles, returns undef.
=cut
sub SSSP_Bellman_Ford {
my ( $G, $s ) = @_;
my ( %weight, %parent );
$weight{ $s } = 0;
my $V = $G->vertices;
my @E = $G->edges;
foreach ( 1..$V ) { # |V|-1 times (*not* |V| times)
my @C = @E; # Copy.
while (my ($u, $v) = splice(@C, 0, 2)) {
my $ow = $weight{ $v };
my $nw = $G->get_attribute( 'weight', $u, $v );
$nw += $weight{ $u } if defined $weight{ $u };
# Relax the edge $u - $w.
if ( not defined $ow or $ow > $nw ) {
$weight{ $v } = $nw;
$parent{ $v } = $u;
}
}
}
my $negative;
# Warn about detected negative cycles.
while (my ($u, $v) = splice(@E, 0, 2)) {
if ( $weight{ $v } >
$weight{ $u } + $G->get_attribute( 'weight', $u, $v ) ) {
warn "SSSP_Bellman_Ford: negative cycle $u $v\n";
$negative++;
}
}
# Bail out if found negative cycles.
return undef if $negative;
# Otherwise return the SSSP graph.
return $G->_SSSP_construct( $s, \%weight, \%parent );
}
=pod
=item SSSP_DAG
$SSSP = $G->SSSP_DAG($s)
Returns the Single-source Shortest Paths (as a graph)
of the DAG $G starting from vertex $s.
=cut
sub SSSP_DAG {
my ( $G, $s ) = @_;
my $SSSP = (ref $G)->new;
my ( %weight, %parent );
$weight{ $s } = 0;
# Because by definition there can be no cycles
# we can freely explore each successor of each vertex.
foreach my $u ( $G->toposort ) {
foreach my $v ( $G->successors( $u ) ) {
my $ow = $weight{ $v };
my $nw = $G->get_attribute( 'weight', $u, $v );
$nw += $weight{ $u } if defined $weight{ $u };
# Relax the edge $u - $v.
if ( not defined $ow or $ow > $nw ) {
$weight{ $v } = $nw;
$parent{ $v } = $u;
}
}
}
return $G->_SSSP_construct( $s, \%weight, \%parent );
}
=pod
=item add_capacity_edge
$G->add_capacity_edge($u, $w, $v, $a)
Adds in the graph $G an edge from vertex $u to vertex $v
and the edge attribute 'capacity' set to $w.
=cut
sub add_capacity_edge {
my ($G, $u, $w, $v, $a) = @_;
$G->add_edge($u, $v);
$G->set_attribute('capacity', $u, $v, $w);
}
=pod
=item add_capacity_edges
$G->add_capacity_edges($u1, $w1, $v1, $u2, $w2, $v2, ...)
Adds in the graph $G the capacity edges.
=cut
sub add_capacity_edges {
my $G = shift;
while (my ($u, $w, $v) = splice(@_, 0, 3)) {
$G->add_capacity_edge($u, $w, $v);
}
}
=pod
=item add_capacity_path
$G->add_capacity_path($v1, $w1, $v2, $w2, ..., $wnm1, $vn)
Adds in the graph $G the n edges defined by the path $v1 ... $vn
with the n-1 'capacity' attributes $w1 ... $wnm1
=cut
sub add_capacity_path {
my $G = shift;
my $u = shift;
while (my ($w, $v) = splice(@_, 0, 2)) {
$G->add_capacity_edge($u, $w, $v);
$u = $v;
}
}
=pod
=item Flow_Ford_Fulkerson
$F = $G->Flow_Ford_Fulkerson($S)
Returns the (maximal) flow network of the flow network $G,
parametrized by the state $S. The $G must have 'capacity'
attributes on its edges. $S->{ source } must contain the
source vertex and $S->{ sink } the sink vertex, and
most importantly $S->{ next_augmenting_path } must contain
an anonymous subroutine which takes $F and $S as arguments
and returns the next potential augmenting path.
Flow_Ford_Fulkerson will do the augmenting.
The result graph $F will have 'flow' and (residual) 'capacity'
attributes on its edges.
=cut
sub Flow_Ford_Fulkerson {
my ( $G, $S ) = @_;
my $F = (ref $G)->new; # The flow network.
my @E = $G->edges;
my ( $u, $v );
# Copy the edges and the capacities, zero the flows.
while (($u, $v) = splice(@E, 0, 2)) {
$F->add_edge( $u, $v );
$F->set_attribute( 'capacity', $u, $v,
$G->get_attribute( 'capacity', $u, $v ) || 0 );
$F->set_attribute( 'flow', $u, $v, 0 );
}
# Walk the augmenting paths.
while ( my $ap = $S->{ next_augmenting_path }->( $F, $S ) ) {
my @aps = @$ap; # augmenting path segments
my $apr; # augmenting path residual capacity
my $psr; # path segment residual capacity
# Find the minimum capacity of the path.
for ( $u = shift @aps; @aps; $u = $v ) {
$v = shift @aps;
$psr = $F->get_attribute( 'capacity', $u, $v ) -
$F->get_attribute( 'flow', $u, $v );
$apr = $psr
if $psr >= 0 and ( not defined $apr or $psr < $apr );
}
if ( $apr > 0 ) { # Augment the path.
for ( @aps = @$ap, $u = shift @aps; @aps; $u = $v ) {
$v = shift @aps;
$F->set_attribute( 'flow',
$u, $v,
$F->get_attribute( 'flow', $u, $v ) +
$apr );
}
}
}
return $F;
}
=pod
=item Flow_Edmonds_Karp
$F = $G->Flow_Edmonds_Karp($source, $sink)
Return the maximal flow network of the graph $G built
using the Edmonds-Karp version of Ford-Fulkerson.
The input graph $G must have 'capacity' attributes on
its edges; resulting flow graph will have 'capacity' and 'flow'
attributes on its edges.
=cut
sub Flow_Edmonds_Karp {
my ( $G, $source, $sink ) = @_;
my $S;
$S->{ source } = $source;
$S->{ sink } = $sink;
$S->{ next_augmenting_path } =
sub {
my ( $F, $S ) = @_;
my $source = $S->{ source };
my $sink = $S->{ sink };
# Initialize our "todo" heap.
unless ( exists $S->{ todo } ) {
# The first element is a hash recording the vertices
# seen so far, the rest are the path from the source.
push @{ $S->{ todo } },
[ { $source => 1 }, $source ];
}
while ( @{ $S->{ todo } } ) {
# $ap: The next augmenting path.
my $ap = shift @{ $S->{ todo } };
my $sv = shift @$ap; # The seen vertices.
my $v = $ap->[ -1 ]; # The last vertex of path.
if ( $v eq $sink ) {
return $ap;
} else {
foreach my $s ( $G->successors( $v ) ) {
unless ( exists $sv->{ $s } ) {
push @{ $S->{ todo } },
[ { %$sv, $s => 1 }, @$ap, $s ];
}
}
}
}
};
return $G->Flow_Ford_Fulkerson( $S );
}
use overload 'eq' => \&eq;
=pod
=item eq
$G->eq($H)
Return true if the graphs (actually, their string representations)
are identical. This means really identical: they must have identical
vertex names and identical edges between the vertices, and they must
be similarly directed. (Just isomorphism isn't enough.)
=cut
sub eq {
my ($G, $H) = @_;
return ref $H ? $G->stringify eq $H->stringify : $G->stringify eq $H;
}
=pod
=back
=head1 COPYRIGHT
Copyright 1999, O'Reilly & Associates.
This code is distributed under the same copyright terms as Perl itself.
=cut
1;
|