🌟 Solve Spiral Matrix III Like a Pro: Multi-Language Tips 🔥💯
\n\nExplore a collection of solutions to LeetCode problems in multiple programming languages. Each solution includes a detailed explanation and step-by-step app
![Screenshot 2024-07-02 113653.png](https://assets.leetcode.com/users/images/da0c1cef-c938-4555-b8cc-10fb6b7615bd_1723094972.4792967.png)\n\nExplore a collection of solutions to LeetCode problems in multiple programming languages. Each solution includes a detailed explanation and step-by-step approach to solving the problem efficiently. Whether you\'re a beginner looking to learn or an experienced coder seeking optimized solutions, this repository aims to provide clear and insightful approaches to tackling challenging LeetCode problems.\n\n### **Access daily LeetCode Solutions Repo :** [click here](https://github.com/withaarzoo/LeetCode-Solutions)\n\n---\n\n![image.png](https://assets.leetcode.com/users/images/5159fe88-0f60-4b26-ad08-ba626d682f0c_1723094962.1703436.png)\n\n# Spiral Matrix III Solution\n\n## Intuition\nThe problem requires visiting all cells in a matrix in a spiral order starting from a given starting position. The key insight is to simulate the spiral movement while ensuring boundary conditions are handled correctly. We will utilize a direction vector to facilitate movement in the right, down, left, and up directions sequentially.\n\n## Approach\n1. **Initialize**:\n   - A result list to store the coordinates of the visited cells.\n   - A direction list to facilitate movement: right, down, left, and up.\n   - A variable to track the number of steps to move in the current direction.\n   - Variables for the current position and direction.\n\n2. **Simulate Movement**:\n   - Start at the given starting position and add it to the result.\n   - Use a loop to continue moving in a spiral pattern until all cells are visited.\n   - Change direction after moving the required steps in the current direction and increase the number of steps every two turns.\n\n3. **Boundary Check**:\n   - Ensure that only valid coordinates within the matrix bounds are added to the result.\n\n## Complexity\n- **Time Complexity**: \\(O(rows \\times cols)\\) because we visit each cell exactly once.\n- **Space Complexity**: \\(O(rows \\times cols)\\) to store the result.\n\n## Code\n```C++ []\nclass Solution {\npublic:\n    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        vector<vector<int>> result;\n        vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        int steps = 1;\n        int d = 0;\n        int r = rStart, c = cStart;\n        result.push_back({r, c});\n\n        while (result.size() < rows * cols) {\n            for (int i = 0; i < 2; ++i) {\n                for (int j = 0; j < steps; ++j) {\n                    r += directions[d][0];\n                    c += directions[d][1];\n                    if (r >= 0 && r < rows && c >= 0 && c < cols) {\n                        result.push_back({r, c});\n                    }\n                }\n                d = (d + 1) % 4;\n            }\n            ++steps;\n        }\n\n        return result;\n    }\n};\n\n```\n```Java []\nclass Solution {\n    public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        List<int[]> result = new ArrayList<>();\n        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        int steps = 1;\n        int d = 0;\n        int r = rStart, c = cStart;\n        result.add(new int[]{r, c});\n\n        while (result.size() < rows * cols) {\n            for (int i = 0; i < 2; ++i) {\n                for (int j = 0; j < steps; ++j) {\n                    r += directions[d][0];\n                    c += directions[d][1];\n                    if (r >= 0 && r < rows && c >= 0 && c < cols) {\n                        result.add(new int[]{r, c});\n                    }\n                }\n                d = (d + 1) % 4;\n            }\n            ++steps;\n        }\n\n        return result.toArray(new int[result.size()][]);\n    }\n}\n\n```\n```JavaScript []\n/**\n * @param {number} rows\n * @param {number} cols\n * @param {number} rStart\n * @param {number} cStart\n * @return {number[][]}\n */\nvar spiralMatrixIII = function(rows, cols, rStart, cStart) {\n    let result = [];\n    let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n    let steps = 1;\n    let d = 0;\n    let r = rStart, c = cStart;\n    result.push([r, c]);\n\n    while (result.length < rows * cols) {\n        for (let i = 0; i < 2; ++i) {\n            for (let j = 0; j < steps; ++j) {\n                r += directions[d][0];\n                c += directions[d][1];\n                if (r >= 0 && r < rows && c >= 0 && c < cols) {\n                    result.push([r, c]);\n                }\n            }\n            d = (d + 1) % 4;\n        }\n        ++steps;\n    }\n\n    return result;\n};\n\n```\n```Python []\nclass Solution:\n    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:\n        result = []\n        directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n        steps = 1\n        d = 0\n        r, c = rStart, cStart\n        result.append([r, c])\n\n        while len(result) < rows * cols:\n            for _ in range(2):\n                for _ in range(steps):\n                    r += directions[d][0]\n                    c += directions[d][1]\n                    if 0 <= r < rows and 0 <= c < cols:\n                        result.append([r, c])\n                d = (d + 1) % 4\n            steps += 1\n\n        return result\n\n```\n```Go []\nfunc spiralMatrixIII(rows int, cols int, rStart int, cStart int) [][]int {\n    result := [][]int{}\n    directions := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}\n    steps := 1\n    d := 0\n    r, c := rStart, cStart\n    result = append(result, []int{r, c})\n\n    for len(result) < rows*cols {\n        for i := 0; i < 2; i++ {\n            for j := 0; j < steps; j++ {\n                r += directions[d][0]\n                c += directions[d][1]\n                if r >= 0 && r < rows && c >= 0 && c < cols {\n                    result = append(result, []int{r, c})\n                }\n            }\n            d = (d + 1) % 4\n        }\n        steps++\n    }\n\n    return result\n}\n\n```\n\n\n## Step-by-Step Detailed Explanation\n\n1. **Initialization**:\n    - **Result List**: The `result` list will store all visited coordinates.\n    - **Direction Vectors**: The `directions` array is initialized with vectors for right, down, left, and up movements.\n    - **Steps**: `steps` is set to 1, representing the initial number of steps in the current direction.\n    - **Direction Index**: `d` is initialized to 0, pointing to the right direction.\n    - **Current Position**: `r` and `c` are initialized to `rStart` and `cStart`.\n\n2. **Starting Position**:\n    - The starting position `[r, c]` is added to the `result` list.\n\n3. **Spiral Movement**:\n    - **Outer Loop**: Continue the loop until the `result` list contains all coordinates (`result.size() < rows * cols`).\n    - **Direction Changes**: Use a nested loop to handle two direction changes (`i < 2`), representing the right-down, left-up sequence.\n    - **Steps in Current Direction**: For each direction, move `steps` times and adjust `r` and `c` according to the current direction vector.\n    - **Boundary Check**: Only add coordinates within grid boundaries to the `result` list.\n    - **Direction Update**: Change the direction using `d = (d + 1) % 4`.\n    - **Steps Update**: Increment `steps` after completing two direction changes.\n\n4. **Returning the Result**:\n    - The final `result` list contains all coordinates in the required spiral order.\n\n---\n\n![upvote cat.png](https://assets.leetcode.com/users/images/94c60ea2-cbcb-4f38-a3d5-6aa325e3787a_1723095114.190211.png)\n
['Array', 'Matrix', 'Simulation', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript']