I'm surprised that the adjacency list is hardcoded in many of these answers. That's the sort of thing the program should work out, so that you can scale the grid to arbitrary sizes. I would have chosen to reference tiles by a co-ordinate pair rather than a plain numbers, so for a grid of size $p by $q, the neighbours of each tile ($x,$y) can be calculated like this:
for (my $y = 1; $y <= $q; $y++) { for (my $x = 1; $x <= $p; $x++) { for (my $ny=$y-1; $ny<=$y+1; $ny++) { next if ($ny < 1 || $ny > $q); for (my $nx=$x-1; $nx<=$x+1; $nx++) { next if ($nx < 1 || $nx > $p || ($nx == $x && $ny == $y)); push @{$adjlist{"$x,$y"}}, [$nx,$ny]; } } } }
But it's easy enough to calculate tile numbers from the co-ordinates in this loop if required. Note the optimisation where we don't bother to go into the deepest loop if we're off the top or bottom edge. You could also do it the opposite way, looping through tile numbers from 1 to ($p*$q) and then effectively calculating the x and y position of the current tile in order to work out whether you are near an edge, but this strikes me as likely to be slower as it involves more arithmetic.

In reply to Re: find all paths of length n in a graph by Anonymous Monk
in thread find all paths of length n in a graph by davidj

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.