BFS and DFS

bfs_edges and dfs_preorder.

bfs_edges is hop order. dfs_preorder_nodes is a recursion-shaped walk. CS taught the idea — here you call nx.

Goal

Print BFS edges from Nairobi and a DFS preorder.

import networkx as nx
G = nx.Graph([('Nairobi', 'Nakuru'), ('Nairobi', 'Mombasa'), ('Nakuru', 'Kisumu')])
print(list(nx.bfs_edges(G, 'Nairobi')))
import networkx as nx
G = nx.Graph([('Nairobi', 'Nakuru'), ('Nakuru', 'Kisumu'), ('Nakuru', 'Eldoret')])
print(list(nx.dfs_preorder_nodes(G, 'Nairobi')))
import networkx as nx
print(list(nx.bfs_tree(nx.path_graph(4), 0).edges()))
import networkx as nx
print(nx.descendants(nx.dfs_tree(nx.path_graph(5), 0), 0))