Matrix and counters out of the matrix in TikZ

Another solution which automatically writes the column labels below the last row elements.

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{matrix}

\begin{document}

\begin{tikzpicture}
\matrix[matrix of math nodes, anchor=south west,
    column sep=-\pgflinewidth,
    row sep=-\pgflinewidth,
    nodes={
        draw=red,
      align=center, 
      outer sep=0pt,
      inner sep=0pt,
      text width=1cm,
      minimum size = 1cm
    },
    row 2/.style={execute at begin cell={%
                |[label={[minimum size=6mm]below:\the\numexpr\pgfmatrixcurrentcolumn-1}]|},}
    ]{
        A & B & D & B & A & C & E & G & E & H & E & C & F & I & F & C & A \\
      0 & 1 & 2 & 1 & 0 & 1 & 2 & 3 & 2 & 3 & 2 & 1 & 2 & 3 & 2 & 1 & 0 \\
    };
\end{tikzpicture}
\end{document}

enter image description here


A very simple one

enter image description here

\documentclass[tikz]{standalone}
\usetikzlibrary{matrix}

\begin{document}

     \begin{tikzpicture}
      \matrix[matrix of math nodes, anchor=south west,
      nodes={
      draw=red,
      align=center, 
      inner sep=0pt,
      text width=1cm - \pgflinewidth,
      minimum size = 1cm - \pgflinewidth
      }
      ]{
        A & B & D & B & A & C & E & G & E & H & E & C & F & I & F & C & A \\
        0 & 1 & 2 & 1 & 0 & 1 & 2 & 3 & 2 & 3 & 2 & 1 & 2 & 3 & 2 & 1 & 0 \\
      };
     \foreach \x in {0,...,16}
      \node[%
       gray,
       anchor=north east,
       align=center,
       text width=\pgflinewidth,
       minimum size = 1cm - \pgflinewidth
       ]%
      at (\x+1,0) {\x};

      \end{tikzpicture}
\end{document}

without matrix, shorter, simpler ?

\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{chains, positioning}

\begin{document}
    \begin{tikzpicture}[
node distance = 0pt,
  start chain = going right,
   box/.style = {draw=red, minimum size=10mm, outer sep=0pt}
                        ]
\foreach \i/\j [count =\k from 0] in {
        A/0, B/1, D/2, B/1, A/0, C/1, E/2, G/3,
        E/2, H/3, E/2, C/1, F/2, I/3, F/2, C/1,
        A/0}
{
\node (n\k) [box,on chain] {\i};
\node [box, below=of n\k, label={[text=gray]below:\k}] {\j};
}
    \end{tikzpicture}
\end{document}

enter image description here