TikZ PGF – Drawing a Simple Fractal

fractalstikz-pgf

I am trying to draw a fractal in tikz that is not a 'common' one – so I'm a little stuck.

It is essentially the Sierpinski Casket but with a square instead of a triangle. Start with the (solid) unit square, remove the centre 9-th, and repeat with the remaining 8 squares. So you end up with 8^k squares of size 1/9^k.

I'd like it to look something like:enter image description here

Preferably the 'last' image will be of stage 5 or 6 but, if possible, a nice definable end stage would be great (like other fractals in LaTeX).

Best Answer

Use the lindenmayersystems of TikZ.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{lindenmayersystems}
\begin{document}
\begin{tikzpicture}[l-system={step=1pt, order=5, angle=90}]
  \pgfdeclarelindenmayersystem{Sierpinski carpet}{
    \rule{F -> F+F-F-FF-F-F-fF}
    \rule{f -> fff}
  }
  \draw l-system [l-system={Sierpinski carpet, axiom=F}];
\end{tikzpicture}
\end{document}

enter image description here