# Typesetting A* in LaTeX using algorithm2e

(See the next iteration.)

The result looks like

and my code is:

\documentclass[10pt]{article}

\usepackage{amsmath}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}

\begin{document}

\begin{algorithm}
\SetKw{Nil}{nil}
\SetKw{Is}{is}
\SetKw{Not}{not}
\SetKw{Mapped}{mapped}
\SetKw{In}{in}
\SetKw{ChildNode}{child node}
\SetKw{Of}{of}
\SetKw{Continue}{continue}
$\text{OPEN} = \{ s \}$ \\
$\text{CLOSED} = \emptyset$ \\
$\pi = \{ (s \mapsto$ \Nil $)\}$ \\
$g = \{ (s \mapsto 0) \}$ \\
\While{$|\text{OPEN}| > 0$}{
$u = \textsc{ExtractMinimum}(\text{OPEN})$ \\
\If{$u$ \Is $t$}{
\KwRet \textsc{TracebackPath}$(u, \pi)$ \\
}
$\text{CLOSED} = \text{CLOSED} \cup \{ u \}$ \\
\ForEach{\ChildNode $v$ \Of $u$}{
\If{$v \in \textsc{CLOSED}$}{
\Continue \\
}
$c = g(u) + w(u, v)$ \\
\If{$v$ \Is \Not \Mapped \In $g$}{
$g(v) = c$ \\
$\pi(v) = u$ \\
\textsc{Insert}$(\text{OPEN}, v, c + h(v))$ \\
}
\ElseIf{$g(v) > c$}{
$g(v) = c$ \\
$\pi(v) = u$ \\
\textsc{DecreaseKey}$(\text{OPEN}, v, c + h(v))$ \\
}
}
}
\KwRet $\langle \rangle$
\caption{\textsc{AStarPathFinder}$(s, t, w, h)$}
\end{algorithm}

\begin{algorithm}
\SetKw{Is}{is}
\SetKw{Not}{not}
\SetKw{Nil}{nil}
$p = \langle \rangle$ \\
\While{$u$ \Is \Not \Nil}{
$p = u \circ p$ \\
$u = \pi(u)$ \\
}
\KwRet $p$
\caption{\textsc{TracebackPath}$(u, \pi)$}
\end{algorithm}

\end{document}


Can I make my code better? For example, is there a way to defined custom keywords in a "global scope" so that I don't have to repeat myself?

• Just define the keywords outside of the algorithm blocks and they will be usable to the end of the document. Commented Dec 6, 2015 at 18:23

Instead of writing \textsc and \text all the time, I prefer semantic markup, such as \func and \var. These simple name changes make the source code easier to read for me. Compare:

\var{p} = \func{prime}(\var{x})
\text{p} = \textsc{prime}(\text{x})


When reading the first line aloud, you will quickly notice any discrepancy between a name and its type.

It looks weird to me that the math mode is closed before the first \Nil and another math mode is opened again immediately after it. This could influence the spacing in subtle ways. It's probably better to write it like this:

$\pi = \{ (s \mapsto \text{\Nil})\}$


This wording feels more natural since there is really only a single math expression here.

The last \caption is not indented properly.

Looks good to me.

As Johannes_B mentioned, hoist (at least three of) the SetKw definitions up to global context, to delete the redundant Is/Not/Nil definitions, and you're done.