Beats 100% Java | C++ | Python | Go | Rust | JavaScript
Approach 1\n# Intuition\nWe\'re dealing with a 2D grid and a pattern of movement that spirals outward from a given starting point. The key insight here is recog
# Approach 1\n# Intuition\nWe\'re dealing with a 2D grid and a pattern of movement that spirals outward from a given starting point. The key insight here is recognizing the regularity in this spiral pattern.\n\nWhen we visualize a spiral, we can see that it consists of a series of "arms" that extend in four directions: right, down, left, and up. Each complete rotation of the spiral increases the length of these arms. This observation forms the foundation of our approach.\n\nAnother crucial insight is that even though we\'re spiraling outwards, we\'re only interested in the cells that fall within our defined grid. This means we need a way to track our position and only record valid coordinates.\n\nLastly, we need to consider how to efficiently generate this spiral pattern. The regularity of the pattern suggests that we could use a systematic approach, possibly involving direction changes and step counts.\n\n# Approach\n\n\n## 1. Direction Management\n\nTo manage the spiral\'s direction, we use a 2D array to represent the four possible movements:\n\n```\nint[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n```\n\nThese correspond to moving right, down, left, and up respectively. By cycling through these directions, we can create our spiral pattern.\n\nWe use a variable `d` to keep track of our current direction:\n\n```\nint d = 0;\n```\n\nAfter each arm of the spiral, we update our direction:\n\n```\nd = (d + 1) % 4;\n```\n\nThis clever use of modulo arithmetic ensures that we cycle through our directions array continuously.\n\n## 2. Step Size Control\n\nA key characteristic of a spiral is that it extends further with each rotation. We manage this with a `steps` variable:\n\n```\nint steps = 0;\n```\n\nWe increment `steps` after moving east (d = 0) or west (d = 2):\n\n```\nif (d == 0 || d == 2) steps++;\n```\n\nThis ensures that our spiral arms grow longer as we progress.\n\n## 3. Grid Traversal\n\nTo traverse the grid, we use our current position (rStart, cStart) and update it based on our current direction and step size:\n\n```\nfor (int i = 0; i < steps; i++) {\n    rStart += directions[d][0];\n    cStart += directions[d][1];\n    // ... (boundary checking and result collection here)\n}\n```\n\nThis loop moves us along one arm of the spiral.\n\n## 4. Boundary Checking\n\nNot all positions in our spiral will be within the grid boundaries. We check each new position:\n\n```\nif (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {\n    // ... (result collection here)\n}\n```\n\nThis ensures we only consider valid grid positions.\n\n## 5. Result Collection\n\nWe collect our results in a 2D array:\n\n```\nint[][] result = new int[rows * cols][2];\n```\n\nEach valid position is added to this array:\n\n```\nresult[count++] = new int[]{rStart, cStart};\n```\n\nWe use a `count` variable to keep track of how many positions we\'ve added, and to determine when we\'ve filled our result array.\n\n## Final Step\n\nThe entire process is wrapped in a while loop that continues until we\'ve collected all the positions in our grid:\n\n```\nwhile (count < rows * cols) {\n    // ... (direction management, step size control, grid traversal, \n    //      boundary checking, and result collection here)\n}\n```\n\n\n# Complexity Analysis\n\n### Time Complexity: O(max(R, C)^2)\n\n**The time complexity of this algorithm is O(max(R, C)^2)**, where R is the number of rows and C is the number of columns in the grid.\n\nTo understand this, let\'s break it down:\n\n1. The spiral pattern we generate is essentially a square with side length max(R, C) * 2. This is because in the worst case, we need to spiral out far enough to reach the farthest corner of our grid.\n\n2. The total number of cells in this larger square is (max(R, C) * 2)^2 = 4 * max(R, C)^2.\n\n3. Our algorithm visits each of these cells exactly once, even though we only record the ones that fall within our actual grid.\n\n4. Therefore, the number of iterations our algorithm performs is proportional to max(R, C)^2.\n\nEven though we\'re only interested in R * C cells, our algorithm may need to visit up to 4 * max(R, C)^2 positions to ensure we\'ve covered all the cells in our grid. This is why the time complexity is quadratic in terms of the larger dimension of the grid.\n\n### Space Complexity\n\n**The space complexity of this algorithm is O(R * C)**, where R is the number of rows and C is the number of columns in the grid.\n\nThis space requirement comes from our result array:\n\n```\nint[][] result = new int[rows * cols][2];\n```\n\nWe\'re storing exactly R * C positions, each represented by a pair of integers.\n\nThis space complexity is optimal for this problem, as we need to return all the positions in the grid. We couldn\'t solve this problem with less space, as the output itself requires O(R * C) space.\n\nAdditional space used by our algorithm (for variables like `steps`, `d`, `rStart`, `cStart`, etc.) is constant and doesn\'t grow with the size of the input, so it doesn\'t affect our space complexity analysis.\n\n### Code\n```Java []\nclass Solution {\n    public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // East, South, West, North\n        int[][] result = new int[rows * cols][2];\n        int steps = 0, d = 0, len = 0;\n        \n        result[0] = new int[]{rStart, cStart};\n        int count = 1;\n        \n        while (count < rows * cols) {\n            if (d == 0 || d == 2) steps++; // Increase step size after moving East or West\n            \n            for (int i = 0; i < steps; i++) {\n                rStart += directions[d][0];\n                cStart += directions[d][1];\n                \n                if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {\n                    result[count++] = new int[]{rStart, cStart};\n                }\n                \n                if (count == rows * cols) return result;\n            }\n            \n            d = (d + 1) % 4; // Change direction\n        }\n        \n        return result;\n    }\n}\n```\n```C++ []\nclass Solution {\npublic:\n    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // East, South, West, North\n        vector<vector<int>> result = {{rStart, cStart}};\n        int steps = 0, d = 0;\n        \n        while (result.size() < rows * cols) {\n            if (d == 0 || d == 2) steps++;\n            \n            for (int i = 0; i < steps; i++) {\n                rStart += directions[d][0];\n                cStart += directions[d][1];\n                \n                if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {\n                    result.push_back({rStart, cStart});\n                }\n                \n                if (result.size() == rows * cols) return result;\n            }\n            \n            d = (d + 1) % 4;\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        directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]  # East, South, West, North\n        result = [[rStart, cStart]]\n        steps = d = 0\n        \n        while len(result) < rows * cols:\n            if d % 2 == 0:\n                steps += 1\n            \n            for _ in range(steps):\n                rStart += directions[d][0]\n                cStart += directions[d][1]\n                \n                if 0 <= rStart < rows and 0 <= cStart < cols:\n                    result.append([rStart, cStart])\n                \n                if len(result) == rows * cols:\n                    return result\n            \n            d = (d + 1) % 4\n        \n        return result\n```\n```Go []\nfunc spiralMatrixIII(rows int, cols int, rStart int, cStart int) [][]int {\n    directions := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} // East, South, West, North\n    result := [][]int{{rStart, cStart}}\n    steps, d := 0, 0\n    \n    for len(result) < rows*cols {\n        if d%2 == 0 {\n            steps++\n        }\n        \n        for i := 0; i < steps; i++ {\n            rStart += directions[d][0]\n            cStart += directions[d][1]\n            \n            if rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols {\n                result = append(result, []int{rStart, cStart})\n            }\n            \n            if len(result) == rows*cols {\n                return result\n            }\n        }\n        \n        d = (d + 1) % 4\n    }\n    \n    return result\n}\n```\n```Rust []\nimpl Solution {\n    pub fn spiral_matrix_iii(rows: i32, cols: i32, r_start: i32, c_start: i32) -> Vec<Vec<i32>> {\n        let directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]; // East, South, West, North\n        let mut result = vec![vec![r_start, c_start]];\n        let (mut steps, mut d) = (0, 0);\n        let (mut r, mut c) = (r_start, c_start);\n        \n        while result.len() < (rows * cols) as usize {\n            if d % 2 == 0 {\n                steps += 1;\n            }\n            \n            for _ in 0..steps {\n                r += directions[d].0;\n                c += directions[d].1;\n                \n                if r >= 0 && r < rows && c >= 0 && c < cols {\n                    result.push(vec![r, c]);\n                }\n                \n                if result.len() == (rows * cols) as usize {\n                    return result;\n                }\n            }\n            \n            d = (d + 1) % 4;\n        }\n        \n        result\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    const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // East, South, West, North\n    const result = [[rStart, cStart]];\n    let steps = 0, d = 0;\n    \n    while (result.length < rows * cols) {\n        if (d % 2 === 0) steps++;\n        \n        for (let i = 0; i < steps; i++) {\n            rStart += directions[d][0];\n            cStart += directions[d][1];\n            \n            if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {\n                result.push([rStart, cStart]);\n            }\n            \n            if (result.length === rows * cols) return result;\n        }\n        \n        d = (d + 1) % 4;\n    }\n    \n    return result;\n};\n```\n---\n# Approach 2\n# Intuition\n\nBuilding upon our understanding from the previous approach, we can further refine our strategy for solving the Spiral Matrix III problem. While the core concept of generating a spiral pattern remains the same, this alternative approach takes a different perspective on managing the spiral\'s progression.\nThe key insight here is to view the spiral not as a series of directional movements, but as a set of expanding boundaries. Imagine drawing a box around our starting point and then systematically expanding this box outward. As we expand, we traverse the perimeter of this box, but only within the confines of our actual grid.\nThis boundary-based thinking leads to a more structured approach, where we can clearly define the limits of our spiral at each step. It also allows us to pre-calculate the valid ranges for each directional movement, potentially reducing the number of boundary checks we need to perform.\n\n# Approach\n\nOur approach to solving this problem involves simulating the spiral movement while efficiently tracking our position and the visited cells. Here\'s a detailed breakdown of the solution:\n\n1. **Initialization:**\n   We start by setting up our data structures and initial state:\n   - Create a 2D array `path` to store the sequence of visited positions.\n   - Initialize boundary variables (`leftBound`, `rightBound`, `topBound`, `bottomBound`) to keep track of the extent of our spiral.\n   - Set a `currentIndex` to keep track of how many valid positions we\'ve recorded.\n\n2. **Main Loop:**\n   We enter a main loop that continues until we\'ve visited all cells in the grid. In each iteration, we perform four movements corresponding to the four directions of the spiral:\n\n   a. Move East (Right):\n      - We traverse from `leftBound + 1` to `rightBound`, staying within the grid\'s column bounds.\n      - We add each valid position to our `path`.\n      - After this movement, we expand our `bottomBound`.\n\n   b. Move South (Down):\n      - We traverse from `topBound + 1` to `bottomBound`, staying within the grid\'s row bounds.\n      - We add each valid position to our `path`.\n      - After this movement, we contract our `leftBound`.\n\n   c. Move West (Left):\n      - We traverse from `rightBound - 1` to `leftBound`, staying within the grid\'s column bounds.\n      - We add each valid position to our `path`.\n      - After this movement, we contract our `topBound`.\n\n   d. Move North (Up):\n      - We traverse from `bottomBound - 1` to `topBound`, staying within the grid\'s row bounds.\n      - We add each valid position to our `path`.\n      - After this movement, we expand our `rightBound`.\n\n3. **Boundary Checks:**\n   Before each directional movement, we check if the movement would be within or touch the grid:\n   - For eastward movement: `topBound >= 0`\n   - For southward movement: `rightBound < cols`\n   - For westward movement: `bottomBound < rows`\n   - For northward movement: `leftBound >= 0`\n   These checks ensure we don\'t unnecessarily compute positions that are entirely outside the grid.\n\n4. **Position Recording:**\n   As we traverse in each direction, we only record positions that are within the grid boundaries. This is done efficiently in the directional traversal methods (`traverseEast`, `traverseSouth`, `traverseWest`, `traverseNorth`).\n\n5. **Termination:**\n   After each directional movement, we check if we\'ve recorded all the required positions (`currentIndex >= totalCells`). If so, we break out of the main loop.\n\n6. **Return Result:**\n   Once we\'ve visited all cells or completed our spiral, we return the `path` array containing all the recorded positions.\n\nKey Aspects of the Approach:\n\n1. Boundary Management:\n   The use of `leftBound`, `rightBound`, `topBound`, and `bottomBound` variables is crucial. These variables effectively represent the "bounding box" of our spiral at any given moment. After each directional movement, we adjust these boundaries, which naturally expands our spiral.\n\n2. Efficient Position Recording:\n   By checking grid boundaries in our traversal methods, we ensure that we only record valid positions. This eliminates the need for additional checks when adding positions to our path.\n\n3. Directional Traversal:\n   The four traversal methods (`traverseEast`, `traverseSouth`, `traverseWest`, `traverseNorth`) encapsulate the logic for moving in each direction. This modular approach makes the code more readable and maintainable.\n\n4. Early Termination:\n   By checking if we\'ve recorded all required positions after each directional movement, we can terminate the process as soon as we\'ve visited all grid cells, avoiding unnecessary computations.\n\n5. Flexibility:\n   This approach works regardless of the starting position or grid size. It naturally handles cases where the starting position is not at the grid\'s corner or center.\n\n**Implementation Details:**\n\n1. The `initializeBounds` method sets up the initial state of our boundaries based on the starting position. We initialize `rightBound` to `cStart + 1` to prepare for the first eastward movement.\n\n2. The `addToPath` method encapsulates the logic of adding a position to our path and incrementing the `currentIndex`. This abstraction simplifies the traversal methods and centralizes the position recording logic.\n\n3. In each traversal method, we use a for-loop to move along the current edge of our spiral. The loop bounds are carefully chosen to respect both the spiral\'s current extent and the grid\'s boundaries.\n\n4. The main `spiralMatrixIII` method orchestrates the entire process, calling the appropriate traversal methods and adjusting boundaries as needed.\n\n\n### Complexity\n\n- **Time Complexity: O(max(rows, cols)^2)**\n\n  The time complexity of this solution is quadratic in terms of the larger dimension of the grid. Here\'s why:\n\n  1. In the worst case, we need to visit all cells in the grid, which is rows * cols.\n  2. However, our spiral pattern extends beyond the grid boundaries.\n  3. The number of steps in each direction increases by 1 after every two movements (right-down or left-up).\n  4. The maximum number of steps in any direction is bounded by max(rows, cols).\n  5. Therefore, the total number of positions we consider (including those outside the grid) is proportional to max(rows, cols)^2.\n\n  It\'s important to note that while we consider positions outside the grid, we only record positions within the grid. This means that for a very large grid with a starting position near the center, we might approach O(rows * cols) operations. However, for the general case and especially when starting near a corner, the O(max(rows, cols)^2) bound holds.\n\n- **Space Complexity: O(rows * cols)**\n\n  The space complexity is linear in terms of the total number of cells in the grid:\n\n  1. We create a 2D array `path` to store all the visited positions within the grid.\n  2. The size of this array is exactly rows * cols, as we need to visit every cell in the grid exactly once.\n  3. Besides the `path` array, we only use a constant amount of additional space for our boundary variables and loop counters.\n\nNote that while our spiral pattern extends beyond the grid, we only store positions that fall within the grid boundaries. This keeps our space complexity directly proportional to the size of the input grid, regardless of how far our spiral extends beyond it.\n\n\n# Code\n```Java []\nclass Solution {\n    int leftBound, topBound, rightBound, bottomBound, currentIndex;\n    int[][] path;\n\n    public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        int totalCells = cols * rows;\n        path = new int[totalCells][];\n        \n        initializeBounds(rStart, cStart);\n        addToPath(rStart, cStart);\n        \n        while (currentIndex < totalCells) {\n            if (topBound >= 0) {\n                traverseEast(Math.max(0, leftBound + 1), Math.min(cols - 1, rightBound));\n            }\n            bottomBound++;\n            if (currentIndex >= totalCells) break;\n            \n            if (rightBound < cols) {\n                traverseSouth(Math.max(0, topBound + 1), Math.min(rows - 1, bottomBound));\n            }\n            leftBound--;\n            if (currentIndex >= totalCells) break;\n            \n            if (bottomBound < rows) {\n                traverseWest(Math.min(cols - 1, rightBound - 1), Math.max(0, leftBound));\n            }\n            topBound--;\n            if (currentIndex >= totalCells) break;\n            \n            if (leftBound >= 0) {\n                traverseNorth(Math.min(rows - 1, bottomBound - 1), Math.max(0, topBound));\n            }\n            rightBound++;\n            if (currentIndex >= totalCells) break;\n        }\n        \n        return path;\n    }\n\n    private void initializeBounds(int rStart, int cStart) {\n        leftBound = rightBound = cStart;\n        topBound = bottomBound = rStart;\n        currentIndex = 0;\n        rightBound++;\n    }\n\n    private void addToPath(int row, int col) {\n        path[currentIndex++] = new int[]{row, col};\n    }\n\n    private void traverseEast(int start, int end) {\n        for (int i = start; i <= end; i++) addToPath(topBound, i);\n    }\n\n    private void traverseWest(int start, int end) {\n        for (int i = start; i >= end; i--) addToPath(bottomBound, i);\n    }\n\n    private void traverseSouth(int start, int end) {\n        for (int i = start; i <= end; i++) addToPath(i, rightBound);\n    }\n\n    private void traverseNorth(int start, int end) {\n        for (int i = start; i >= end; i--) addToPath(i, leftBound);\n    }\n}\n```\n```C++ []\nclass Solution {\nprivate:\n    int rows, cols, leftBound, topBound, rightBound, bottomBound;\n    vector<vector<int>> path;\n\n    void addToPath(int row, int col) {\n        if (row >= 0 && row < rows && col >= 0 && col < cols) {\n            path.push_back({row, col});\n        }\n    }\n\n    void traverseEast(int start, int end) {\n        for (int i = start; i <= end; ++i) addToPath(topBound, i);\n    }\n\n    void traverseWest(int start, int end) {\n        for (int i = start; i >= end; --i) addToPath(bottomBound, i);\n    }\n\n    void traverseSouth(int start, int end) {\n        for (int i = start; i <= end; ++i) addToPath(i, rightBound);\n    }\n\n    void traverseNorth(int start, int end) {\n        for (int i = start; i >= end; --i) addToPath(i, leftBound);\n    }\n\npublic:\n    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {\n        this->rows = rows;\n        this->cols = cols;\n        int totalCells = rows * cols;\n        path.reserve(totalCells);\n\n        leftBound = rightBound = cStart;\n        topBound = bottomBound = rStart;\n        ++rightBound;\n\n        addToPath(rStart, cStart);\n\n        while (path.size() < totalCells) {\n            if (topBound >= 0) traverseEast(max(0, leftBound + 1), min(cols - 1, rightBound));\n            ++bottomBound;\n            if (path.size() >= totalCells) break;\n\n            if (rightBound < cols) traverseSouth(max(0, topBound + 1), min(rows - 1, bottomBound));\n            --leftBound;\n            if (path.size() >= totalCells) break;\n\n            if (bottomBound < rows) traverseWest(min(cols - 1, rightBound - 1), max(0, leftBound));\n            --topBound;\n            if (path.size() >= totalCells) break;\n\n            if (leftBound >= 0) traverseNorth(min(rows - 1, bottomBound - 1), max(0, topBound));\n            ++rightBound;\n            if (path.size() >= totalCells) break;\n        }\n\n        return path;\n    }\n};\n```\n```Python []\nclass Solution:\n    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:\n        total_cells = rows * cols\n        path = []\n        left_bound = right_bound = cStart\n        top_bound = bottom_bound = rStart\n        right_bound += 1\n\n        def add_to_path(row: int, col: int):\n            if 0 <= row < rows and 0 <= col < cols:\n                path.append([row, col])\n\n        add_to_path(rStart, cStart)\n\n        while len(path) < total_cells:\n            if top_bound >= 0:\n                for col in range(max(0, left_bound + 1), min(cols, right_bound) + 1):\n                    add_to_path(top_bound, col)\n            bottom_bound += 1\n            if len(path) >= total_cells:\n                break\n\n            if right_bound < cols:\n                for row in range(max(0, top_bound + 1), min(rows, bottom_bound) + 1):\n                    add_to_path(row, right_bound)\n            left_bound -= 1\n            if len(path) >= total_cells:\n                break\n\n            if bottom_bound < rows:\n                for col in range(min(cols - 1, right_bound - 1), max(-1, left_bound - 1), -1):\n                    add_to_path(bottom_bound, col)\n            top_bound -= 1\n            if len(path) >= total_cells:\n                break\n\n            if left_bound >= 0:\n                for row in range(min(rows - 1, bottom_bound - 1), max(-1, top_bound - 1), -1):\n                    add_to_path(row, left_bound)\n            right_bound += 1\n            if len(path) >= total_cells:\n                break\n\n        return path\n```\n```Go []\nfunc spiralMatrixIII(rows int, cols int, rStart int, cStart int) [][]int {\n    totalCells := rows * cols\n    path := make([][]int, 0, totalCells)\n    leftBound, rightBound, topBound, bottomBound := cStart, cStart+1, rStart, rStart\n\n    addToPath := func(row, col int) {\n        if row >= 0 && row < rows && col >= 0 && col < cols {\n            path = append(path, []int{row, col})\n        }\n    }\n\n    traverseEast := func(start, end int) {\n        for i := start; i <= end; i++ {\n            addToPath(topBound, i)\n        }\n    }\n\n    traverseWest := func(start, end int) {\n        for i := start; i >= end; i-- {\n            addToPath(bottomBound, i)\n        }\n    }\n\n    traverseSouth := func(start, end int) {\n        for i := start; i <= end; i++ {\n            addToPath(i, rightBound)\n        }\n    }\n\n    traverseNorth := func(start, end int) {\n        for i := start; i >= end; i-- {\n            addToPath(i, leftBound)\n        }\n    }\n\n    addToPath(rStart, cStart)\n\n    for len(path) < totalCells {\n        if topBound >= 0 {\n            traverseEast(max(0, leftBound+1), min(cols-1, rightBound))\n        }\n        bottomBound++\n        if len(path) >= totalCells {\n            break\n        }\n\n        if rightBound < cols {\n            traverseSouth(max(0, topBound+1), min(rows-1, bottomBound))\n        }\n        leftBound--\n        if len(path) >= totalCells {\n            break\n        }\n\n        if bottomBound < rows {\n            traverseWest(min(cols-1, rightBound-1), max(0, leftBound))\n        }\n        topBound--\n        if len(path) >= totalCells {\n            break\n        }\n\n        if leftBound >= 0 {\n            traverseNorth(min(rows-1, bottomBound-1), max(0, topBound))\n        }\n        rightBound++\n        if len(path) >= totalCells {\n            break\n        }\n    }\n\n    return path\n}\n\nfunc max(a, b int) int {\n    if a > b {\n        return a\n    }\n    return b\n}\n\nfunc min(a, b int) int {\n    if a < b {\n        return a\n    }\n    return b\n}\n```\n```Rust []\nimpl Solution {\n    pub fn spiral_matrix_iii(rows: i32, cols: i32, r_start: i32, c_start: i32) -> Vec<Vec<i32>> {\n        let total_cells = (rows * cols) as usize;\n        let mut path = Vec::with_capacity(total_cells);\n        let (mut left_bound, mut right_bound, mut top_bound, mut bottom_bound) = (c_start, c_start + 1, r_start, r_start);\n\n        let add_to_path = |row: i32, col: i32, path: &mut Vec<Vec<i32>>| {\n            if row >= 0 && row < rows && col >= 0 && col < cols {\n                path.push(vec![row, col]);\n            }\n        };\n\n        let traverse_east = |start: i32, end: i32, top: i32, path: &mut Vec<Vec<i32>>| {\n            for i in start..=end {\n                add_to_path(top, i, path);\n            }\n        };\n\n        let traverse_west = |start: i32, end: i32, bottom: i32, path: &mut Vec<Vec<i32>>| {\n            for i in (end..=start).rev() {\n                add_to_path(bottom, i, path);\n            }\n        };\n\n        let traverse_south = |start: i32, end: i32, right: i32, path: &mut Vec<Vec<i32>>| {\n            for i in start..=end {\n                add_to_path(i, right, path);\n            }\n        };\n\n        let traverse_north = |start: i32, end: i32, left: i32, path: &mut Vec<Vec<i32>>| {\n            for i in (end..=start).rev() {\n                add_to_path(i, left, path);\n            }\n        };\n\n        add_to_path(r_start, c_start, &mut path);\n\n        while path.len() < total_cells {\n            if top_bound >= 0 {\n                traverse_east(0.max(left_bound + 1), (cols - 1).min(right_bound), top_bound, &mut path);\n            }\n            bottom_bound += 1;\n            if path.len() >= total_cells {\n                break;\n            }\n\n            if right_bound < cols {\n                traverse_south(0.max(top_bound + 1), (rows - 1).min(bottom_bound), right_bound, &mut path);\n            }\n            left_bound -= 1;\n            if path.len() >= total_cells {\n                break;\n            }\n\n            if bottom_bound < rows {\n                traverse_west((cols - 1).min(right_bound - 1), 0.max(left_bound), bottom_bound, &mut path);\n            }\n            top_bound -= 1;\n            if path.len() >= total_cells {\n                break;\n            }\n\n            if left_bound >= 0 {\n                traverse_north((rows - 1).min(bottom_bound - 1), 0.max(top_bound), left_bound, &mut path);\n            }\n            right_bound += 1;\n            if path.len() >= total_cells {\n                break;\n            }\n        }\n\n        path\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    const totalCells = rows * cols;\n    const path = [];\n    let [leftBound, rightBound, topBound, bottomBound] = [cStart, cStart + 1, rStart, rStart];\n\n    const addToPath = (row, col) => {\n        if (row >= 0 && row < rows && col >= 0 && col < cols) {\n            path.push([row, col]);\n        }\n    };\n\n    const traverseEast = (start, end) => {\n        for (let i = start; i <= end; i++) addToPath(topBound, i);\n    };\n\n    const traverseWest = (start, end) => {\n        for (let i = start; i >= end; i--) addToPath(bottomBound, i);\n    };\n\n    const traverseSouth = (start, end) => {\n        for (let i = start; i <= end; i++) addToPath(i, rightBound);\n    };\n\n    const traverseNorth = (start, end) => {\n        for (let i = start; i >= end; i--) addToPath(i, leftBound);\n    };\n\n    addToPath(rStart, cStart);\n\n    while (path.length < totalCells) {\n        if (topBound >= 0) traverseEast(Math.max(0, leftBound + 1), Math.min(cols - 1, rightBound));\n        bottomBound++;\n        if (path.length >= totalCells) break;\n\n        if (rightBound < cols) traverseSouth(Math.max(0, topBound + 1), Math.min(rows - 1, bottomBound));\n        leftBound--;\n        if (path.length >= totalCells) break;\n\n        if (bottomBound < rows) traverseWest(Math.min(cols - 1, rightBound - 1), Math.max(0, leftBound));\n        topBound--;\n        if (path.length >= totalCells) break;\n\n        if (leftBound >= 0) traverseNorth(Math.min(rows - 1, bottomBound - 1), Math.max(0, topBound));\n        rightBound++;\n        if (path.length >= totalCells) break;\n    }\n\n    return path;\n};\n```\n\n---\n\n\nHey everyone,\n\n**PLEASE DON\'T UPVOTE THIS POST AT ALL.**\n\nLook, I write these solutions for myself. It\'s just easier to post \'em here than keeping them on my computer or throwing them in a GitHub repo. When I need to revise stuff, I can just come back here. Simple.\n\n*If you\'ve got a real question, sure, drop a comment. I\'ll try to help if I can. If you find the solution helpful, good for you. If you don\'t, I\'m sorry. And if you\'ve got something to add like advice, optimization, or anything useful just drop a comment. But for god\'s sake, don\'t upvote. People have turned LeetCode into some kinda social media, farming likes as if LeetCode\'s gonna pay them or companies are gonna grab them by the leg and offer them a job. I don\'t want any of that nonsense.\nso please, DO NOT UPVOTE THIS POST. I mean it.*\n\nOnce posts hit the top 4-5 solutions, things get messy real fast. You get all this spam, bots, random unrelated comments, Fake-real and stupid upvote/downvote drama. I want none of that BS.\nSo if you see this post going above 2-3 upvotes, even a downvote is better than an upvote.\n\nThanks for getting it.\n
['Array', 'Matrix', 'Simulation', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript']