Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: find all paths of length n in a graph

by Anonymous Monk
on Jan 17, 2006 at 16:35 UTC ( [id://523771]=note: print w/replies, xml ) Need Help??


in reply to find all paths of length n in a graph

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://523771]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-25 17:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found