54. Spiral Matrix

ArrayMatrixSimulation

Explanation:

To traverse the matrix in a spiral order, we can repeatedly extract the outermost ring of the matrix until the matrix is empty. We keep track of the boundaries of the current ring and move in four directions (right, down, left, up) while adding elements to the result list.

  • Algorithmic Idea:

    1. Initialize four variables to keep track of the boundaries of the current ring: top, bottom, left, right.
    2. Traverse the matrix in a spiral order by moving right, down, left, and up, while updating the boundaries and adding elements to the result list.
    3. Repeat the process until the matrix is empty.
  • Time Complexity: O(m * n) where m is the number of rows and n is the number of columns in the matrix.

  • Space Complexity: O(1) excluding the result list.

:

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return result;
        }
        
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;
        
        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            top++;
            
            for (int i = top; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            right--;
            
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }
                bottom--;
            }
            
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
                left++;
            }
        }
        
        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.