[LeetCode] 54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return
[1,2,3,6,9,8,7,4,5]
.
Thought process:
Keep left, right, top, bottom boundaries of the spiral. Iterate the top row, right column, bottom row, and left column. If after any row or column iteration, left and right or top and bottom cross, we can get out of the loop.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> spiral = new ArrayList<>(); int m = matrix.length; if (m == 0) { return spiral; } int n = matrix[0].length; int left = 0; int right = n - 1; int top = 0; int bottom = m - 1; while (true) { for (int i = left; i <= right; i++) { spiral.add(matrix[top][i]); } top++; if (top > bottom) { break; } for (int i = top; i <= bottom; i++) { spiral.add(matrix[i][right]); } right--; if (right < left) { break; } for (int i = right; i >= left; i--) { spiral.add(matrix[bottom][i]); } bottom--; if (bottom < top) { break; } for (int i = bottom; i >= top; i--) { spiral.add(matrix[i][left]); } left++; if (left > right) { break; } } return spiral; } } |
Time complexity: O(mn).
Comments
Post a Comment