Solution beat 100% | PHP
Intuition\n Describe your first thoughts on how to solve this problem. \n- To traverse all the cells in a grid of size rows * cols starting from a specific posi
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- To traverse all the cells in a grid of size `rows * cols` starting from a specific position (`rStart`, `cStart`) in a spiral order, we can use an array of directions and a variable to keep track of the number of steps needed in each direction.\n- We will move in sequential directions: **right, down, left, and up**, increasing the number of steps after every two directions (one complete cycle).\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize necessary variables such as the direction array, total number of cells, starting position, initial step count, and direction index.\n- Use a while loop to continue until we have added all the cells to the result array.\n- Inside the while loop, use a nested for loop. The outer loop runs twice for each direction (to ensure we change direction after every two edges), and the inner loop moves the required number of steps in the current direction.\n- Check if the new position is within the grid bounds, and if so, add that position to the result array.\n- After every two directions, increment the number of steps required.\n# Complexity\n- Time complexity: **O(n\xD7m)**\n\nWe will traverse all cells in the grid once, so the time complexity is linear with respect to the number of cells in the grid, or `O(n\xD7m)`, where `n` is the number of rows and `m` is the number of columns.\n\n- Space complexity: **O(n\xD7m)**\n\nThe result array `ans` will contain all positions of the grid, so the space complexity is also linear with respect to the number of cells in the grid, or `O(n\xD7m)`.\n# Code\n```\nclass Solution\n{\n    /**\n     * @param Integer $rows\n     * @param Integer $cols\n     * @param Integer $rStart\n     * @param Integer $cStart\n     * @return Integer[][]\n     */\n    public static function spiralMatrixIII($rows, $cols, $rStart, $cStart) {\n        $directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n        $totalCells = $rows * $cols;\n        $r = $rStart;\n        $c = $cStart;\n        $steps = 1;\n        $directionIndex = 0;\n        $ans = [[$r, $c]];\n        \n        while (count($ans) < $totalCells) {\n            for ($i = 0; $i < 2; $i++) {\n                for ($j = 0; $j < $steps; $j++) {\n                    $r += $directions[$directionIndex][0];\n                    $c += $directions[$directionIndex][1];\n                    if ($r >= 0 && $r < $rows && $c >= 0 && $c < $cols) {\n                        $ans[] = [$r, $c];\n                    }\n                }\n                $directionIndex = ($directionIndex + 1) % 4;\n            }\n            $steps++;\n        }\n        return $ans;\n    }\n}\n\n```
['Array', 'PHP', 'Matrix', 'Simulation']