Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 54. Spiral Matrix #15

Open
Woodyiiiiiii opened this issue Apr 18, 2020 · 0 comments
Open

LeetCode 54. Spiral Matrix #15

Woodyiiiiiii opened this issue Apr 18, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

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

Example 2:

Input:
[
  [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]

四个点(left, right, top, bottom)来标志一个圆环,每次都缩短。

还要注意边界情况,即剩下的中心图样不是正方形,而是线状或者一个点,所以需要判断四个点中两对对应点的关系来判断。

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new LinkedList();
        int m = matrix.length;
        if (m == 0) {
            return res;
        }
        int n = matrix[0].length;
        // if (n == 0) {
        //     return res;
        // }
        int left = 0, right = n - 1, top = 0, bottom = m - 1;
        int i = 0, j = 0;
        while (left <= right && top <= bottom) {
            for (j = left; j <= right; ++j) {
                res.add(matrix[top][j]);
            }
            if (top == bottom) {
                break;
            }
            for (i = top + 1; i <= bottom; ++i) {
                res.add(matrix[i][right]);
            }
            if (left == right) {
                break;
            }
            for (j = right - 1; j >= left; --j) {
                res.add(matrix[bottom][j]);
            }
            for (i = bottom - 1; i > top; --i) {
                res.add(matrix[i][left]);
            }
            ++left;
            ++top;
            --right;
            --bottom;
        }
        
        return res;
    }
}

参考资料:

LeetCode原题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant