Skip to content

Instantly share code, notes, and snippets.

@zr-tex8r
Created June 28, 2022 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zr-tex8r/63d1a5d27820f743cf993aca711cca2e to your computer and use it in GitHub Desktop.
Save zr-tex8r/63d1a5d27820f743cf993aca711cca2e to your computer and use it in GitHub Desktop.
TeX: Depth-first search
%#!latex
% 0-2-4-6-8
% 0######### How many moves are
% :# # # # needed to go
% 2# ## ## from (1,1) to (7,1) ?
% :### # #
% 4# # #
% :#########
\makeatletter
\newcount\my@x \newcount\my@y \newcount\my@m
\def\my@untr{-1}% untraversed
\@tfor\my@p:=%
{1,1}{3,1}{4,1}{6,1}{7,1}{1,2}{2,2}{3,2}%
{6,2}{3,3}{5,3}{6,3}{7,3}{1,4}{2,4}{3,4}%
{4,4}{5,4}{7,4}\do{%
\@namedef{my@(\my@p)}{-1}}
\def\my@nameedef#1{\expandafter\edef\csname#1\endcsname}
\def\my@one@step(#1,#2)#3\relax{%
\my@x=#1 \my@y=#2 \def\my@pos@stack{#3}%
\my@m=\numexpr\@nameuse{my@(#1,#2)}+1\relax
\my@add@step{1}{0}\my@add@step{0}{1}%
\my@add@step{-1}{0}\my@add@step{0}{-1}}
\def\my@add@step#1#2{%
\def\my@p{\the\numexpr\my@x+#1,\the\numexpr\my@y+#2}%
\expandafter\ifx\csname my@(\my@p)\endcsname\my@untr
\my@nameedef{my@(\my@p)}{\the\my@m}%
\edef\my@pos@stack{(\my@p)\my@pos@stack}%
\fi}
\@namedef{my@(1,1)}{0}
\def\my@pos@stack{(1,1)}
\@whilesw\unless\ifx\my@pos@stack\@empty\fi{%
\expandafter\my@one@step\my@pos@stack\relax}
% Show the answer!
\typeout{***Answer=\@nameuse{my@(7,1)}}
\stop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment