Skip to main content
5 of 20
deleted 6 characters in body
640KB
  • 11.9k
  • 2
  • 35
  • 57

PHP, 385 335 307 293 bytes

function c(&$m,$x,$r=-1,$l=0,$d=0){if($r<0)$r=array_search(P,$m);$m[$l=$r]='.';if(!in_array(T,$m))die;foreach([L=>$r%$x?$r-1:0,U=>$m[$r-$x]?$r-$x:0,D=>$m[$r+$x]?$r+$x:0,R=>$r%$x<$x-1?$r+1:0]as$o=>$n)if($n&&$m[$n]!=M&&$m[$n]!='.'){echo$o;c($m,$x,$n,$r,$o);}if($l)echo[L=>R,R=>L,U=>D,D=>U][$d];}

Uses a recursive depth-first search to crawl the map until all treasures are found.

Input is a one-dimensional array map, and number of columns s( $m, 13 );, output list to STDOUT.

Ungolfed

This could stand a bit more golfing (and possibly a bit more cleverness).

function c( &$m, $x, $r=-1, $l=0, $d=0 ) {

    // locate starting position on first call
    if( $r < 0 )                        
        $r = array_search( 'P', $m );

    // move to new room
    $l = $r;

    // room is marked with . to show it has been visited
    $m[ $r ] = '.';

    // end if no more treasures
    if ( ! in_array( 'T', $m ) )
        exit;

    // generate list of adjacent rooms (this needs work)
    foreach ( [
        'L' => $r % $x ? $r-1 : false,
        'U' => isset($m[ $r - $x ]) ? $r - $x : false, 
        'D' => isset($m[ $r + $x ]) ? $r + $x : false, 
        'R' => $r % $x < $x-1 ? $r+1 : false
    ] as $o => $n )
        if ( $n && $m[$n] != 'M' && $m[$n] != '.' ) {
            // if not a Mountain and not visited display the direction
            echo $o;
            // and recursively keep crawling
            c( $m, $x, $n, $r, $o );
        }

    // if recursive branch has ended, go back to previous square
    if ( $l )
        echo ['L'=>'R','R'=>'L','U'=>'D','D'=>'U'][$d]; // display the reverse direction name

}

Basic Case

DDDDDRUUUUURDDRUURDDRUURDDDLDLLLDRRRRURUUUURDDDDDLRRU

Locked Up

DDRUURDD

No Treasure:

 (no output)

Back Alley

DDDDDRUUUUURDDDDDRUUUUURDDDDDRUUUUURDDDDDRUUUUURRRRRLLLLLDDRRRRRLLLLLDDRRRRR

No way to move

  (no output)

1x1

  (no output)

Hedge Maze (an original creation)

+-+-+-+-+-+-+-+-+-+-+-+-+-+
|P|M| |T|M| | | |M| |M|M|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |M| |M| | |M|T|M|T| | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T| | |M| |M| |T|M|M|M| |M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M| | | |M| |M|M| | | |M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T| | |M| |M| | | | |M| |M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M| |T| | |M|M|M|M|M| |T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+

DDRRUURLDDDDLLRRDRRUULRUURURRDDLDDRRRURRUULLUDRRRUDLDDDDR

640KB
  • 11.9k
  • 2
  • 35
  • 57