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 59. Spiral Matrix II #16

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

LeetCode 59. Spiral Matrix II #16

Woodyiiiiiii opened this issue Apr 18, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Apr 18, 2020

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example 1:

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

I题一样的思路。又因为这是正方形矩阵,中间的剩余部分的边界判断可以省略。

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        if (n == 0) {
            return matrix;
        }
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        int i = 0, j = 0;
        int val = 1;
        while (left <= right && top <= bottom) {
            for (j = left; j <= right; ++j) {
                matrix[top][j] = val++;
            }
            if (top == bottom) {
                break;
            }
            for (i = top + 1; i <= bottom; ++i) {
                matrix[i][right] = val++;
            }
            if (left == right) {
                break;
            }
            for (j = right - 1; j >= left; --j) {
                matrix[bottom][j] = val++;
            }
            for (i = bottom - 1; i > top; --i) {
                matrix[i][left] = val++;
            }
            ++left;
            ++top;
            --right;
            --bottom;
        }
        
        return matrix;
    }
}

参考资料:
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