DEV Community

Discussion on: Daily Challenge #288 - Maze Runner

Collapse
 
peter279k profile image
peter279k

Here is the simple way with PHP to traverse two dimensional arrays and get current moving states :).

function maze_runner($maze, $directions): string {
  $m = 0;
  $n = 0;
  $startM = 0;
  $startN = 0;
  foreach ($maze as $mazeRow) {
    foreach ($mazeRow as $mazeNumber) {
      if ($mazeNumber === 2) {
        $startM = $m;
        $startN = $n;
        break;
      }
      $n += 1;
    }
    $n = 0;
    $m += 1;
  }

  $currentValue = null;
  foreach ($directions as $direction) {
    if ($direction === 'N') {
      $startM -= 1;
      if ($startM < 0 || $startM >= count($maze[0])) {
        return 'Dead';
      }
    }
    if ($direction === 'S') {
      $startM += 1;
      if ($startM < 0 || $startM >= count($maze[0])) {
        return 'Dead';
      }
    }
    if ($direction === 'E') {
      $startN += 1;
      if ($startN < 0 || $startN >= count($maze[0])) {
        return 'Dead';
      }
    }
    if ($direction === 'W') {
      $startN -= 1;
      if ($startN < 0 || $startN >= count($maze[0])) {
        return 'Dead';
      }
    }

    $currentValue = $maze[$startM][$startN];

    if ($currentValue === 3) {
      return 'Finish';
    }
    if ($currentValue === 1) {
      return 'Dead';
    }
  }

  return 'Lost';
}