We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
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原题
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example 1:
跟I题一样的思路。又因为这是正方形矩阵,中间的剩余部分的边界判断可以省略。
参考资料:
LeetCode原题
The text was updated successfully, but these errors were encountered: