Spiral Matrix III

Updated on 08 July, 2025
Spiral Matrix III header image

Problem Statement

In this computational problem, you are given a starting point (rStart, cStart) within a grid defined by its dimensions, rows x cols. Positioned in the grid facing east, your task is to traverse the entire grid in a unique pattern: a clockwise spiral starting from the initial location. Despite the bounds of the grid, your movement can extend outside these bounds momentarily, potentially returning later. The movement continues until every cell within the dimensions rows x cols is visited. You must report the travel log as a list of grid coordinates in the exact order each was visited. This will help understand spatial patterns and movement within bounded grids, especially useful for robotics and simulation algorithms.

Examples

Example 1

Input:

rows = 1, cols = 4, rStart = 0, cStart = 0

Output:

[[0,0],[0,1],[0,2],[0,3]]

Example 2

Input:

rows = 5, cols = 6, rStart = 1, cStart = 4

Output:

[[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]

Constraints

  • 1 <= rows, cols <= 100
  • 0 <= rStart < rows
  • 0 <= cStart < cols

Approach and Intuition

The challenge involves simulating a walk in a spiral pattern, starting at a specified cell of the grid and navigating through all cells using specific movement rules:

  1. Start facing east at position (rStart, cStart).
  2. Move east as long as there are unvisited cells or until the boundary is reached, then move to the next available direction in the clockwise direction (south).
  3. Continue changing your movement to the next clockwise direction (west, north, and so forth) every time you either reach an edge or need to start moving inward.
  4. If during traveling in any direction, a boundary is encountered, turn right (clockwise) irrespective of whether the boundary is physically the edge of the grid or a traverse limitation due to earlier paths.
  5. Continue this pattern until all cells of the grid are covered.

The overall approach can be broken into handling directional movement and detecting boundary conditions:

  • Directional Control: Starting from facing east, you must effectively manage turning right (thus facing south, then west, and then north, repeating the cycle) whenever a blockage or the end of the grid is encountered.
  • Boundary and Path Memory: A tracking system to remember which cells have been visited is crucial. Once an edge is reached or you return to a previously visited cell, turn right.

This problem can be approached programmatically using a loop to handle the continuous movement and an array (or similar data structure) to keep track of visited cells. It tests not only the understanding of array manipulations but also control flow in terms of loop and directional changes based on runtime conditions.

Solutions

  • C++
cpp
class Solution {
public:
    vector<vector<int>> generateSpiral(int R, int C, int xStart, int yStart) {
        // Directions follow the pattern: right, down, left, up
        vector<vector<int>> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        vector<vector<int>> resultMatrix;
    
        // Start with a single step and rotate direction as outer loop iterates
        for (int len = 1, dirIdx = 0; resultMatrix.size() < R * C;) {
            // Loop twice for each side of the rectangle length 'len'
            for (int k = 0; k < 2; ++k) {
                for (int count = 0; count < len; ++count) {
                    // Check if the current position is within bounds
                    if (xStart >= 0 && xStart < R && yStart >= 0 && yStart < C) {
                        resultMatrix.push_back({xStart, yStart});
                    }
                    // Move to the next position in the current direction
                    xStart += directions[dirIdx][0];
                    yStart += directions[dirIdx][1];
                }
                // Switch to the next direction
                dirIdx = (dirIdx + 1) % 4;
            }
            // Increase the side length after each full iteration of inner loops
            ++len;
        }
        return resultMatrix;
    }
};

Generate a matrix filled with coordinates in a spiral pattern starting from a given position within bounds. This method is implemented in C++ and is capable of providing a spiral traversal of matrix coordinates.

  1. Initialize a sequence of movement directions to simulate traveling right, down, left, and up, in order to create a spiral pattern.
  2. Prepare an empty list to hold the result of matrix coordinates.
  3. Employ a nested loop structure where the outer loop determines the spiral pattern's expansion and the inner loops handle the movement across and down the matrix for a given length.
  4. For each position calculated by the current direction and step:
    • Verify whether this position is within the matrix boundaries of dimensions RxC.
    • If valid, append the coordinate to the results list.
    • Update the position based on the current direction.
  5. After tackling one dimension of movement (either horizontal or vertical), rotate to the next direction.
  6. With each full cycle of the four directions, increase the length of steps to progressively expand the spiral.

After iterating through all possible positions while expanding the steps as needed, the method will produce a complete set of coordinates filled in a spiral order starting from the specified position, ensuring all coordinates are within the matrix limits. This function specifically caters to the need for generating a pathway in a matrix for visual or computational purposes.

  • Java
java
class Solution {
    
    public int[][] generateSpiral(int row_count, int col_count, int start_row, int start_col) {
        // Direction vectors for East, South, West, North
        int[][] directions = new int[][] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
        int[][] path = new int[row_count * col_count][2];
        int pathIndex = 0;
    
        // Step variable and rotation of direction using mod 4
        for (int length = 1, dir = 0; pathIndex < row_count * col_count;) {
            for (int z = 0; z < 2; ++z) {
                for (int stepIndex = 0; stepIndex < length; ++stepIndex) {
                    // Only add indexes within bounds
                    if (
                        start_row >= 0 &&
                        start_row < row_count &&
                        start_col >= 0 &&
                        start_col < col_count
                    ) {
                        path[pathIndex][0] = start_row;
                        path[pathIndex][1] = start_col;
                        ++pathIndex;
                    }
                    // Move to the next spot on the grid
                    start_row += directions[dir][0];
                    start_col += directions[dir][1];
                }
    
                dir = (dir + 1) % 4;
            }
            ++length;
        }
        return path;
    }
}

In the Java solution for generating a spiral matrix starting from a specified cell within a matrix grid, the process follows these primary steps:

  1. Initialize direction vectors corresponding to moving East, South, West, and North. This array of vectors guides movements through the matrix in a spiral pattern.

  2. Create an output array named path that will store each cell's coordinates the spiral traverses. Its size is determined by the total number of cells (row_count * col_count).

  3. Use a nested loop strategy for spiral traversal:

    • The outer loop manages the expansion of the spiral. The spiral length increases after every full cycle (East to North) through the directions.
    • Two nested loops, the first handles the cycle through the directions, and the second iterates the movement for each direction according to the current spiral length.
  4. For each potential cell in the spiral:

    • Check if it's within the matrix bounds.
    • If so, log the cell's coordinates in the path array and increment the count of visited cells.
  5. Move to the next cell in the current direction as dictated by the directions array.

  6. Every two steps in any direction, turn 90 degrees to continue the spiral pattern.

  7. Return the path array as the final ordered list of coordinates representing the spiral path.

This logic effectively simulates a spiral traversal starting from any coordinate in the grid, yielding a sequential list of matrix coordinates that follow a spiral order. This can be particularly useful for matrix-based simulations or visualizations where directional and orderly coverage of a grid is required.

  • Python
python
class Solution:
    def traverseSpiral(self, height: int, width: int, xStart: int, yStart: int) -> List[List[int]]:
        # Array of directions: right, down, left, up
        directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        result = []
    
        # Beginning with 1 step, and the initial direction is 0 (East)
        steps = 1
        current_direction = 0
        while len(result) < height * width:
            # Process each direction twice before increasing steps
            for _ in range(2):
                for _ in range(steps):
                    # Check if the current position is valid
                    if (0 <= xStart < height) and (0 <= yStart < width):
                        result.append([xStart, yStart])
                    # Update position based on the current direction
                    xStart += directions[current_direction][0]
                    yStart += directions[current_direction][1]
    
                # Change direction clockwise
                current_direction = (current_direction + 1) % 4
            # Increase the number of steps every two directions
            steps += 1
        return result

This solution involves generating coordinates for a matrix as they would be visited in a spiral order starting from a given initial position (xStart, yStart). The code is implemented in Python and defines a method called traverseSpiral within a class named Solution. Here's how it works:

  • Starts by defining the directions list which contains steps for traversal in the order of right [0, 1], down [1, 0], left [0, -1], and up [-1, 0].
  • An empty list result is initialized to store the resulting path of coordinates.
  • The spiral traversal is controlled by the steps variable which initially is set to 1, indicative of the number of steps to move in a current direction.
  • A current_direction index is used to cycle through the directions list.
  • The function enters a loop that will continue until the result list has accumulated enough coordinates to match the total number of cells in the matrix (i.e., height * width).
  • Inside the loop, for each iteration of the directions (right then down, left then up), the steps are executed:
    • Coordinates are checked for their validity (i.e., whether they lie within the bounds of the matrix).
    • Valid coordinates are added to the result.
    • Position indices xStart and yStart are updated based on the current direction.
  • After exiting the innermost loop, the direction is rotated clockwise by updating the current_direction index.
  • Every two directions, the number of steps is increased, as per the spiral's expanding nature.
  • Finally, the method returns the result which is a list of coordinates representing the matrix cells in the order they are visited in a spiral traversal.

This method ensures comprehensive traversal of a matrix in a spiral order from any provided starting point, making it versatile for various starting positions within the bounds of the matrix.

Comments

No comments yet.