2

I'm working on a graph theory problem, and need to map out a grid of nodes/vertices that denote their degree, and illustrates their paths. The graph I need is basically a 7 x 7 grid, that shows the amount of moves a knight on a chessboard would have if they occupied a location. I would like the color to darken as the degree increases.

The grid I need is identical to the blue 7 by 7 image in the third answer on this page, or shown below.

7x7 map

I've tried modifying a bunch of examples I've found online, but I cannot create something quite like this.

3

Here I use TeX counters to do some basic calculations but pgfmath could also be used. The code uses two nested foreach to loop over all the cells. On each cell at (\x,\y) an inner foreach loops over all possible horses jumps (\px,\py). If the jump is outside the chessboard it is not counted. The number of valid moves is accumulated in \n (remember to assign to it using \global or the value would be lost outside the body of the loop). Then we draw the edges (on the background to avoid edges going over nodes drawn later); I avoid drawing the same line twice by just drawing the "forward" jumps. The fill color is obtained by just multiplying the number of jumps by 10 to obtain a sensible percentage to blend blue with.

\documentclass[tikz]{standalone}

\pgfdeclarelayer{background}
\pgfsetlayers{background,main}

\begin{document}
\begin{tikzpicture}

\newcount\n
\newcount\px
\newcount\py
\newcount\ncolor
\foreach \x in {1,...,8}{
    \foreach \y in {1,...,8}{
        \n=0
        \foreach \dx/\dy in {-2/-1,-1/-2,1/-2,2/-1,2/1,1/2,-1/2,-2/1}{
            \px=\x
            \py=\y
            \advance\px by \dx\relax
            \advance\py by \dy\relax
            \ifnum\px>0
            \ifnum\px<9
            \ifnum\py>0
            \ifnum\py<9
                \global\advance\n by 1\relax
                \begin{pgfonlayer}{background}
                    \ifnum\dx=2
                        \draw (\x,\y) -- (\px,\py);
                    \fi
                    \ifnum\dy=2
                        \draw (\x,\y) -- (\px,\py);
                    \fi
                \end{pgfonlayer}
            \fi\fi\fi\fi
        }
        \ncolor=\n
        \multiply\ncolor by 10
        \node[draw,circle,fill={blue!\the\ncolor}] at (\x,\y) {\the\n};
    }
}
\end{tikzpicture}
\end{document}

And here's the result:

preview

A trick to avoid the \ncolor counter, if you are happy with the 10 factor for the color:

\node[draw,circle,fill={blue!\the\n0}] at (\x,\y) {\the\n};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.