A bit late, but out of curiosity i tried this in php by first getting the location of the princess, then the location of mario follwed by a loop to move Mario around. This wins the game but it's not the fastest way, especially when the grid is big.
function displayPathtoPrincess($m, $grid) {
//get mario and princesses locations
$gridstring = implode('', $grid);
$p = strpos($gridstring, 'p') + 1;
$m = strpos($gridstring, 'm') + 1;
$positioncount = 0;
//get marios and princess xy location
for ($x = 0; $x < count($grid); $x ++) {
for ($y = 0; $y < count($grid); $y ++) {
$positioncount ++;
if ($positioncount == $m) {
$mario[0] = $x;
$mario[1] = $y;
}
if ($positioncount == $p) {
$princess[0] = $x;
$princess[1] = $y;
}
if (isset($mario) > 0 && isset($princess) > 0)
break;
}
}
//Find princess
$moves = '';
for ($x = 0; $x < count($grid); $x ++) {
for ($y = 0; $y < count($grid); $y ++) {
//if at marios location ...
if ($mario[0] == $x && $mario[1] == $y) {
$updownmove = $princess[0] - $mario[0];
if ($updownmove < 0) {
for (; $updownmove < 0; $updownmove++) {
$newposition = $mario[0] - 1;
if ($newposition >= 0) {
$mario[0] = $newposition;
if (trim($moves) != '') {
$moves .= "\n";
}
$moves .= "UP";
}
}
} else {
for (; $updownmove > 0; $updownmove--) {
$mario[0] = $mario[0] + 1;
if (trim($moves) != '') {
$moves .= "\n";
}
$moves .= "DOWN";
}
}
$rightleftmove = $princess[1] - $mario[1];
if ($rightleftmove < 0) {
for (; $rightleftmove < 0; $rightleftmove++) {
$newposition = $mario[1] - 1;
if ($newposition >= 0) {
$mario[1] = $newposition;
if (trim($moves) != '') {
$moves .= "\n";
}
$moves .= "LEFT";
}
}
} else {
for (; $rightleftmove > 0; $rightleftmove--) {
$mario[1] = $mario[1] + 1;
if (trim($moves) != '') {
$moves .= "\n";
}
$moves .= "RIGHT";
}
}
}
if (isfound($mario, $princess)) {
echo $moves;
return;
}
}
}
}
function isfound($mario, $princess) {
if (count($mario) == 0)
return false;
if (($mario[0] == $princess[0]) && ($mario[1] == $princess[1])) {
return true;
} else {
return false;
}
}