dfs_labeled_edges#

dfs_labeled_edges(G, source=None, depth_limit=None)[source]#

Iterate over edges in a depth-first-search (DFS) labeled by type.

Parameters:
GNetworkX graph
sourcenode, optional

Specify starting node for depth-first search and return edges in the component reachable from source.

depth_limitint, optional (default=len(G))

Specify the maximum search depth.

Returns:
edges: generator

A generator of triples of the form (u, v, d), where (u, v) is the edge being explored in the depth-first search and d is one of the strings ā€˜forwardā€™, ā€˜nontreeā€™, ā€˜reverseā€™, or ā€˜reverse-depth_limitā€™. A ā€˜forwardā€™ edge is one in which u has been visited but v has not. A ā€˜nontreeā€™ edge is one in which both u and v have been visited but the edge is not in the DFS tree. A ā€˜reverseā€™ edge is one in which both u and v have been visited and the edge is in the DFS tree. When the depth_limit is reached via a ā€˜forwardā€™ edge, a ā€˜reverseā€™ edge is immediately generated rather than the subtree being explored. To indicate this flavor of ā€˜reverseā€™ edge, the string yielded is ā€˜reverse-depth_limitā€™.

Notes

If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched.

The implementation of this function is adapted from David Eppsteinā€™s depth-first search function in PADS, with modifications to allow depth limits based on the Wikipedia article ā€œDepth-limited searchā€.

Examples

The labels reveal the complete transcript of the depth-first search algorithm in more detail than, for example, dfs_edges():

>>> from pprint import pprint
>>>
>>> G = nx.DiGraph([(0, 1), (1, 2), (2, 1)])
>>> pprint(list(nx.dfs_labeled_edges(G, source=0)))
[(0, 0, 'forward'),
 (0, 1, 'forward'),
 (1, 2, 'forward'),
 (2, 1, 'nontree'),
 (1, 2, 'reverse'),
 (0, 1, 'reverse'),
 (0, 0, 'reverse')]