MrainW's Home

All things come to those who wait!

0%

LeetCode 54. Spiral Matrix

Question

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

https://leetcode.com/problems/spiral-matrix/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new LinkedList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
int left = 0, right = matrix[0].length - 1;
int top = 0, bottom = matrix.length - 1;
while (left < right && top < bottom) {
for (int i = left; i < right; i++) res.add(matrix[top][i]);
for (int i = top; i < bottom; i++) res.add(matrix[i][right]);
for (int i = right; i > left; i--) res.add(matrix[bottom][i]);
for (int i = bottom; i > top; i--) res.add(matrix[i][left]);
left++;
right--;
top++;
bottom--;
}
if (left == right) {
for (int i = top; i <= bottom; i++) res.add(matrix[i][left]);
} else if (top == bottom) {
for (int i = left; i <= right; i++) res.add(matrix[top][i]);
}
return res;
}
}

Complexity:

Time complexity: O(mn)

Space complexity: O(mn)

Welcome to my other publishing channels