Given a network , we wish to find paths from a source node to every reachable node . There are several algorithms which can do this for us with various pros and cons, we focus on generic search.
In generic search, nodes are in one of two states: marked or unmarked. All marked nodes are known to be reachable from our source node . Notice that if is marked, is unmarked and the network has an arc , then we can mark node . We refer to arcs as admissible if node is marked and node is unmarked. Otherwise, the arc is inadmissible.
The search algorithm will traverse the marked nodes in a certain order. We track this order with an array where is the order of node in the traversal. We also keep track of a second array where indicates that we marked node after traveling along arc . The combination of and define a search tree on the nodes in which contains all nodes reachable from .
The algorithm also keeps track of a list of nodes which contains all nodes with potential admissible out arcs. If a node does not have an admissible out arc, we remove it from . Whenever we mark a node , we add to .
The full algorithm is given below:
Algorithm 6 Generic Search
procedure Search()
unmark all nodes in
mark node
while do
select a node from
if node is incident to an admissible arc then
mark node
add node to
else
delete node from
end if
end while
end procedure
The algorithm runs in time.
Breadth-First vs Depth-First Search
Depending on how we select nodes from , we may get different search trees. If we maintain as a first-in, first-out (FIFO) queue, then we get breadth-first search (BFS). In BFS, we mark all admissible arcs that node is incident to before moving deeper into the tree.
Property. In the breadth-first search tree, the tree path from the source node to any node is a shortest path in terms of number of arcs.
If we instead maintain as a last-in, first out (LIFO) stack, then we get depth-first search (DFS). In this case, we move as deep as possible into the network first.
Property. In depth-first search, the following two properties hold:
- If node is a descendant of node and , then .
- All the descendants of any node are ordered consecutively in sequence.
Reverse Search
In reverse search, instead of starting at a source node and finding paths to each node , we instead start at a terminus node and find all paths from to . This can still be done with generic search with a couple tweaks. We initialize instead; while examining a node , we look for incoming arcs of the node. Moreover, we now consider an arc admissible if is unmarked and is marked.