% Author: Marc van Dongen
% Source: http://www.texample.net/tikz/examples/hilbert-curve/
\newdimen\HilbertLastX
\newdimen\HilbertLastY
\newcounter{HilbertOrder}

\def\DrawToNext#1#2{%
   \advance \HilbertLastX by #1
   \advance \HilbertLastY by #2
   \pgfpathlineto{\pgfqpoint{\HilbertLastX}{\HilbertLastY}}
   % Alternative implementation using plot streams:
   % \pgfplotstreampoint{\pgfqpoint{\HilbertLastX}{\HilbertLastY}}
}

% \Hilbert[right_x,right_y,left_x,left_x,up_x,up_y,down_x,down_y]
\def\Hilbert[#1,#2,#3,#4,#5,#6,#7,#8] {
  \ifnum\value{HilbertOrder} > 0%
     \addtocounter{HilbertOrder}{-1}
     \Hilbert[#5,#6,#7,#8,#1,#2,#3,#4]
     \DrawToNext {#1} {#2}
     \Hilbert[#1,#2,#3,#4,#5,#6,#7,#8]
     \DrawToNext {#5} {#6}
     \Hilbert[#1,#2,#3,#4,#5,#6,#7,#8]
     \DrawToNext {#3} {#4}
     \Hilbert[#7,#8,#5,#6,#3,#4,#1,#2]
     \addtocounter{HilbertOrder}{1}
  \fi
}


% \hilbert((x,y),order)
\def\hilbert((#1,#2),#3){%
   \advance \HilbertLastX by #1
   \advance \HilbertLastY by #2
   \pgfpathmoveto{\pgfqpoint{\HilbertLastX}{\HilbertLastY}}
   % Alternative implementation using plot streams:
   % \pgfplothandlerlineto
   % \pgfplotstreamstart
   % \pgfplotstreampoint{\pgfqpoint{\HilbertLastX}{\HilbertLastY}}
   \setcounter{HilbertOrder}{#3}
   \Hilbert[1mm,0mm,-1mm,0mm,0mm,1mm,0mm,-1mm]
   \pgfusepath{stroke}%
}

\begin{figure}[htp]%
    \centering
    % draw Hilbert curves of order n=1,...,5
    % Warning! Curves with order > 6 may crash TeX
    \subfloat[$n=1$]{\tikz[scale=18] \hilbert((0mm,0mm),1);}~~
    \subfloat[$n=2$]{\tikz[scale=6] \hilbert((0mm,0mm),2);}~~
    \subfloat[$n=3$]{\tikz[scale=2.6] \hilbert((0mm,0mm),3);}~~
    \subfloat[$n=4$]{\tikz[scale=1.2] \hilbert((0mm,0mm),4);}~~
    \subfloat[$n=5$]{\tikz[scale=0.58] \hilbert((0mm,0mm),5);}%
    \caption{Hilbert-Kurve}\xindex{Hilbert-Kurve}
    \label{fig:hilbert-curve}
\end{figure}%
