1 ! Copyright (C) 2008 William Schlieper <schlieper@unc.edu>
2 ! See http://factorcode.org/license.txt for BSD license.
4 USING: kernel combinators fry continuations sequences arrays vectors assocs hashtables heaps namespaces ;
12 GENERIC: vertices ( graph -- seq ) flushable
14 GENERIC: num-vertices ( graph -- n ) flushable
16 GENERIC: num-edges ( graph -- n ) flushable
18 GENERIC: adjlist ( from graph -- seq ) flushable
20 GENERIC: adj? ( from to graph -- ? ) flushable
22 GENERIC: add-blank-vertex ( index graph -- )
24 GENERIC: delete-blank-vertex ( index graph -- )
26 GENERIC: add-edge* ( from to graph -- )
28 GENERIC: add-edge ( u v graph -- )
30 GENERIC: delete-edge* ( from to graph -- )
32 GENERIC: delete-edge ( u v graph -- )
38 [ vertices ] [ '[ _ adjlist length ] map sum ] bi ;
41 [ vertices ] [ swapd '[ _ swap _ adj? ] filter ] bi ;
44 swapd adjlist index >boolean ;
47 [ add-edge* ] [ swapd add-edge* ] 3bi ;
50 [ delete-edge* ] [ swapd delete-edge* ] 3bi ;
52 : add-blank-vertices ( seq graph -- )
53 '[ _ add-blank-vertex ] each ;
55 : delete-vertex ( index graph -- )
57 [ '[ _ _ 3dup adj? [ delete-edge* ] [ 3drop ] if ] each ]
58 [ delete-blank-vertex ] 2tri ;
62 : search-wrap ( quot graph -- ? )
63 [ [ graph set ] [ vertices [ f 2array ] map >hashtable visited? set ] bi
64 [ t ] compose [ dup end-search? [ drop f ] [ rethrow ] if ] recover ] with-scope ; inline
66 : (depth-first) ( v pre post -- )
67 { [ 2drop visited? get t -rot set-at ]
69 [ [ graph get adjlist ] 2dip
70 '[ dup visited? get at [ drop ] [ _ _ (depth-first) ] if ] each ]
71 [ nip call ] } 3cleave ; inline
75 : depth-first ( v graph pre post -- ?list ? )
76 '[ _ _ (depth-first) visited? get ] swap search-wrap ; inline
78 : full-depth-first ( graph pre post tail -- ? )
79 '[ [ visited? get [ nip not ] assoc-find ]
80 [ drop _ _ (depth-first) @ ]
81 [ 2drop ] while ] swap search-wrap ; inline
84 V{ } clone swap [ 2dup swap push dupd
85 '[ _ swap graph get adj? not ] all?
86 [ end-search ] unless ]
87 [ drop dup pop* ] [ ] full-depth-first nip ;
89 : topological-sort ( graph -- seq/f )
91 [ V{ } swap [ drop ] [ prefix ] [ ] full-depth-first drop ]