[leetcode] Spiral Matrix II
2014-06-26 20:13
309 查看
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =3,
You should return the following matrix:
https://oj.leetcode.com/problems/spiral-matrix-ii/
思路:按要求输出,注意边界。
第二遍记录:边界处理问题参考前一题。
For example,
Given n =3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
https://oj.leetcode.com/problems/spiral-matrix-ii/
思路:按要求输出,注意边界。
public class Solution { public int[][] generateMatrix(int n) { int[][] mat = new int ; if (n <= 0) return mat; int num = 1; int left = 0; int right = n - 1; int top = 0; int bottom = n - 1; while (num <= n * n) { int i; for (i = left; i <= right; i++) mat[top][i] = num++; for (i = top + 1; i <= bottom; i++) mat[i][right] = num++; if (top < bottom) for (i = right - 1; i >= left; i--) mat[bottom][i] = num++; if (left < right) for (i = bottom - 1; i >= top + 1; i--) mat[i][left] = num++; top++; left++; bottom--; right--; } return mat; } public static void main(String[] args) { System.out.println(new Solution().generateMatrix(1)); } }
第二遍记录:边界处理问题参考前一题。
相关文章推荐
- [LeetCode]59 Spiral Matrix II
- 【leetcode】59.Spiral Matrix II
- [Leetcode] Spiral Matrix II (Java)
- Leetcode 细节实现题 Spiral Matrix II
- [LeetCode] Spiral Matrix II
- leetcode--Spiral Matrix II
- Leetcode Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- Spiral Matrix II 产生正方形的旋转矩阵@LeetCode
- [LeetCode] Spiral Matrix II
- LeetCode-Spiral Matrix II
- #leetcode#Spiral Matrix II
- 【leetcode】Spiral Matrix II
- LeetCode Spiral Matrix II
- LeetCode Spiral Matrix II
- LeetCode Spiral Matrix II
- [LeetCode]Spiral Matrix II
- LeetCode Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode---Spiral Matrix II