What are some common algorithms used to find the optimal path through a maze-like array filled with 0s and 1s in PHP?

When trying to find the optimal path through a maze-like array filled with 0s and 1s in PHP, one common algorithm is Depth First Search (DFS). DFS explores as far as possible along each branch before backtracking. Another common algorithm is Breadth First Search (BFS), which explores all the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. Both algorithms can be used to find the optimal path through a maze-like array.

function findOptimalPath($maze) {
    $rows = count($maze);
    $cols = count($maze[0]);
    $visited = array_fill(0, $rows, array_fill(0, $cols, false));
    $queue = [[0, 0, 0]]; // [row, col, steps]
    
    while (!empty($queue)) {
        $current = array_shift($queue);
        $row = $current[0];
        $col = $current[1];
        $steps = $current[2];
        
        if ($row < 0 || $row >= $rows || $col < 0 || $col >= $cols || $maze[$row][$col] == 1 || $visited[$row][$col]) {
            continue;
        }
        
        if ($row == $rows - 1 && $col == $cols - 1) {
            return $steps;
        }
        
        $visited[$row][$col] = true;
        
        $queue[] = [$row + 1, $col, $steps + 1];
        $queue[] = [$row - 1, $col, $steps + 1];
        $queue[] = [$row, $col + 1, $steps + 1];
        $queue[] = [$row, $col - 1, $steps + 1];
    }
    
    return -1; // no path found
}

// Example usage
$maze = [
    [0, 1, 0, 0],
    [0, 0, 0, 1],
    [1, 1, 0, 0],
    [0, 0, 1, 0]
];

echo findOptimalPath($maze);