Description

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

Example 1:

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

Spiral Matrix

Example 2:

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

Spiral Matrix Example 2

Constraints:

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

Solution

This solution requires applying complex logic based on the navigation we want to perform. So, not so much logical in this case. It simply uses loop and conditionals.

 1class Solution {
 2    public List<Integer> spiralOrder(int[][] matrix) {
 3        int m = matrix.length, n = matrix[0].length;
 4        int top = 0, bottom = m - 1, left = 0, right = n - 1;
 5        List<Integer> result = new ArrayList<>();
 6        while (left <= right && top <= bottom) {
 7            for (int j = left; j <= right; ++j) {
 8                result.add(matrix[top][j]);
 9            }
10            for (int i = top + 1; i <= bottom; ++i) {
11                result.add(matrix[i][right]);
12            }
13            if (left < right && top < bottom) {
14                for (int j = right - 1; j >= left; --j) {
15                    result.add(matrix[bottom][j]);
16                }
17                for (int i = bottom - 1; i > top; --i) {
18                    result.add(matrix[i][left]);
19                }
20            }
21            top++;
22            bottom--;
23            left++;
24            right--;
25        }
26        return result;
27    }
28}