Depending on your data, you might save a lot of memory by changing from

$paths->[0][0][0] = [ [ 3, 0, 0 ], ]; $paths->[0][1][0] = [ [ 0, 2, 0 ], ]; ...
to
$paths->{0,0,0} = [ join($;, 3,0,0), ]; $paths->{0,1,0} = [ join($;, 0,2,0), ]; ...

For starters, you have way fewer values, and hashes are better for sparse data. You could even pack the data down if you know the range of the numbers.

sub to_key { my ($x, $y, $s) = @_; return pack 'L', ($x-MIN_X) * (MAX_Y-MIN_Y) * (MAX_S-MIN_S) + ($y-MIN_Y) * (MAX_S-MIN_S) + ($s-MIN_S) } sub fr_key { my $key = unpack 'L', $_[0]; return ( int( $key / (MAX_Y-MIN_Y) / (MAX_S-MIN_S) ) + MI +N_X, int( $key / (MAX_S-MIN_S) ) % (MAX_Y-MIN_Y) + MI +N_Y, int( $key ) % (MAX_S-MIN_S) + MI +N_S, ); } $paths->{to_key(0,0,0)} = join '', to_key(3,0,0), ); $paths->{to_key(0,1,0)} = join '', to_key(0,2,0), ); ...

fr_key( substr($branches, $i*4, 4) ) would be used instead of @{ $branches->[$i] }.


Aside from that, moving to an iterator (as you suggested) would also help. Your current function generates *all* paths before returning. Instead, it could return a path as soon as it finds one.


But before you do anything, are you sure the deep recursion is simply deep (not a problem, except you might run out of memory) and not infinite?


In reply to Re: Eliminating Recursive Tree Walking by using MJD-style Infinite Streams? by ikegami
in thread Eliminating Recursive Tree Walking by using MJD-style Infinite Streams? by jryan

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.