DEV Community

Wenqi Jiang
Wenqi Jiang

Posted on

54. Spiral Matrix

Description

Given an m x n matrix, return all elements of the matrix in spiral order.

💡 Note:

Example 1:

Untitled

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Enter fullscreen mode Exit fullscreen mode

Example 2:

Untitled

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • 100 <= matrix[i][j] <= 100

Solutions

Solution 1

Intuition

we need use index to count number, and reduce range step by step

Code

public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> ans = new LinkedList<>();

    // your code goes here
    int rows = matrix.length, columns = matrix[0].length;
    int n = rows * columns;
    int startRow = 0, endRow = rows - 1;
    int startColumn = 0, endColumn = columns - 1;
    int index = 0;
    while (index < n) {
        for (int i = startColumn; i <= endColumn && index < n; i++) {
            ans.add(matrix[startRow][i]);
            index++;
        }
        startRow++;
        for (int i = startRow; i <= endRow && index < n; i++) {
            ans.add(matrix[i][endColumn]);
            index++;
        }
        endColumn--;
        for (int i = endColumn; i >= startColumn && index < n; i--) {
            ans.add(matrix[endRow][i]);
            index++;
        }
        endRow--;
        for (int i = endRow; i >= startRow && index < n; i--) {
            ans.add(matrix[i][startColumn]);
            index++;
        }
        startColumn++;
    }

    return ans;
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(n)
  • Space: O(n)

Top comments (0)