Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

885. Spiral Matrix III

ArrayMatrixSimulation

Explanation

To solve this problem, we can simulate the movement in a spiral order by keeping track of the direction we are moving in. We start at the given cell (rStart, cStart) and keep moving in a spiral pattern until we have visited all cells in the grid.

We can define four directions: right, down, left, and up. We start by moving right, then down, then left, then up, and repeat this pattern while adjusting the boundaries of the grid as we move.

We can keep track of the current position and direction, and iterate until we have visited all cells in the grid.

Time Complexity: O(rows * cols) - we need to visit all cells in the grid once.

Space Complexity: O(rows * cols) - the space required to store the result array.

class Solution {
    public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        int[][] result = new int[rows * cols][2];
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // right, down, left, up
        int direction = 0; // starting with right
        int steps = 1; // number of steps to take in current direction
        int stepCount = 0; // counter for steps taken
        int r = rStart, c = cStart;
        int index = 0;
        
        while (index < rows * cols) {
            if (r >= 0 && r < rows && c >= 0 && c < cols) {
                result[index][0] = r;
                result[index][1] = c;
                index++;
            }
            
            r += directions[direction][0];
            c += directions[direction][1];
            stepCount++;
            
            if (stepCount == steps) {
                direction = (direction + 1) % 4;
                if (direction == 0 || direction == 2) {
                    steps++; // increase steps every two directions
                }
                stepCount = 0;
            }
        }
        
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.