[Tex/LaTex] Algorithm : Command \end{list} invalid in math mode

algorithmsmath-mode

I just started with Latex and I struggle a little bit with algorithm.
Here is the algorithm, I try to show.
But on the line of the first ENDFOR, I have this error

Latex Error: Command \end{list} invalid in math mode
I don't seewhat's wrong with this.

Thank you for your help.

\begin{algorithm}
\caption{Algorithme de Dijkstra}
\begin{algorithmic}[1]
\REQUIRE Un graphe $G$
\REQUIRE Un noeud source $s$
\ENSURE Les plus court chemins de s vers tout les autres noeuds de G $A$
\FORALL{$v \in V[G]$}
    \STATE $d[v] \leftarrow +\infty$ 
    \STATE $previous[v] \leftarrow undefined
\ENDFOR
\STATE $d[s] \leftarrow 0
\STATE $S \leftarrow empty set
\STATE $Q \leftarrow $V[G]
\Loop Q is not an empty set 
    \STATE $u \leftarrow  Extract_Min(Q)
    \STATE $S \leftarrow  S union $u
    \ForAll{edge (u,v) outgoing from u}  
    \IF{d[u] + w(u,v) < d[v]}
        \STATE d[v] \leftarrow d[u] + w(u,v)
        \STATE previous[v] := u 
    \ENDIF
    \EndFor
\EndLoop
\end{algorithmic}
\end{algorithm}

Best Answer

You're not consistent with delimiting math formulas; for instance, in the second \STATE line, you open a math formula, without closing it.

I have tried to make the algorithms more consistent. Note that \LOOP and \Loop are not the same (and the latter is not defined in algorithmic). If you're using a different set of packages, please make it known.

\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algorithmic}

\newcommand{\kw}[1]{\textrm{#1}}

\begin{document}
\begin{algorithm}
\caption{Algorithme de Dijkstra}
\begin{algorithmic}[1]
\REQUIRE Un graphe $G$
\REQUIRE Un noeud source $s$
\ENSURE Les plus court chemins de $s$ vers tout les autres noeuds de $G$ $A$
\FORALL{$v \in V[G]$}
    \STATE $d[v] \leftarrow +\infty$ 
    \STATE $\kw{previous}[v] \leftarrow \kw{undefined}$
\ENDFOR
\STATE $d[s] \leftarrow 0$
\STATE $S \leftarrow \kw{empty set}$
\STATE $Q \leftarrow V[G]$
\LOOP 
    \STATE $Q$ is not an empty set 
    \STATE $u \leftarrow  \kw{Extract}_{\kw{Min}}(Q)$
    \STATE $S \leftarrow  S \cup \{u\}$
    \FORALL{edge $(u,v)$ outgoing from $u$}  
    \IF{$d[u] + w(u,v) < d[v]$}
        \STATE $d[v] \leftarrow d[u] + w(u,v)$
        \STATE $\kw{previous}[v] := u$ 
    \ENDIF
    \ENDFOR
\ENDLOOP
\end{algorithmic}
\end{algorithm}
\end{document}

enter image description here