1. 程式人生 > >leetcode54- Spiral Matrix- medium

leetcode54- Spiral Matrix- medium

ger all elements nts 需要 spa med [] integer

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:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

每一while循環內做一次圈打印。一圈打印做4個for循環,每個for循環做一個方向。做好後更新一下某個方向的邊界。

細節:中間需要檢查一下是否會因為奇數窄形狀導致的同條回蕩。

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

leetcode54- Spiral Matrix- medium