Whatever-First Search, Depth-first search, Breadth-first search topological sort

May 18, 2023

When studying certain properties of graphs, one general concept is to consider the \(\textbf{reachability}\) problem. Given a graph \(G = (V, E)\) and an additional vertex \(s \in V\), we want to know which vertices are reachable from \(s\). We want to find the vertices where there is a path from \(s\) to \(v\) \(( s \rightarrow v)\). One natural tool in any computer science student’s toolbox is the \(\textbf{depth-first search}\) algorithm. Two forms of methods can be constructed: recursively or iteratively. Either method works; under the hood, it doesn’t really matter. Just go with whatever you’re more comfortable with.

Preorder and Postorder

Recollecting \(\textbf{Preorder}\) and \(\textbf{Postorder}\) of rooted trees. If we have a tree noted as \(T\) and subtress as \(T_1, ..., T_k\) and whose root is label \(r\) the two methods are described as follows

\(\textbf{Preorder}\): We visit the root \(r\), and then recursively do a preorder traversal of \(T_1, ... T_k\)
\(\textbf{Postorder}\) We first recursively perform a postorder traversal of the \(T_1, ..., T_k\) subtrees and then visit the root \(r\).

    \begin{algorithm}
    \caption{Preorder}
    \begin{algorithmic}
    \PROCEDURE{PreOrder}{$v$}
        \IF{ $v \not\in V$ }
            \STATE return 
        \ENDIF
        \STATE \textsc{Visit}$(v)$
        \STATE \CALL{PreOder}{$v.left$}
        \STATE \CALL{PreOder}{$v.right$}
    \ENDPROCEDURE
    \end{algorithmic}
    \end{algorithm}
    \begin{algorithm}
    \caption{Postorder}
    \begin{algorithmic}
    \PROCEDURE{PostOrder}{$v$}
        \IF{ $v \not\in V$ }
            \STATE return 
        \ENDIF
        \STATE \CALL{Postorder}{$v.left$}
        \STATE \CALL{Postorder}{$v.right$}
        \STATE \textsc{Visit}$(v)$
    \ENDPROCEDURE
    \end{algorithmic}
    \end{algorithm}

Topological sort

Topological sort (Intro to Algorithms 4th ed.)

    \begin{algorithm}
    \caption{Topological sort}
    \begin{algorithmic}
    \PROCEDURE{Topological-Sort}{$G$}
        \STATE{call \textsc{DFS}$(G)$ to compute finish times $v.f$ for each vertex $v$}
        \STATE{as each vertex is finished, insert it onto the front of a linked list} 
        \STATE{\textbf{return} the linked list of vertices}
    \ENDPROCEDURE
    \end{algorithmic}
    \end{algorithm}