59. Spiral Matrix II
2017-09-18 23:46
295 查看
Given an integer n, generate a square matrix filled with elements from 1 to n2 in
spiral order.
For example,
Given n =
You should return the following matrix:
题意就是做一个n*n的回环。
我的思路是定义x,y记录位置,index记录数值。一圈一圈向内填充。最外层循环4次 每次循环n-1次,最后x=0,y=0。x++,y++后进入更内一层,4*(n-3)的循环,以此类推。
spiral order.
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
题意就是做一个n*n的回环。
我的思路是定义x,y记录位置,index记录数值。一圈一圈向内填充。最外层循环4次 每次循环n-1次,最后x=0,y=0。x++,y++后进入更内一层,4*(n-3)的循环,以此类推。
class Solution { public int[][] generateMatrix(int n) { int num[][] = new int ; int x = 0; int y = 0; int index = 1; for(int i = 1;i<=n/2;i++){ for(int j = 0;j<n+1-i*2;j++){ num[x][y] = index; index++; y++; } for(int j = 0;j<n+1-i*2;j++){ num[x][y] = index; index++; x++; } for(int j = 0;j<n+1-i*2;j++){ num[x][y] = index; index++; y--; } for(int j = 0;j<n+1-i*2;j++){ num[x][y] = index; index++; x--; } x++; y++; } if(n%2 == 1) num[n/2][n/2] = n*n; return num; } }
相关文章推荐
- LeetCode 59 Spiral Matrix II
- 个人记录-LeetCode 59. Spiral Matrix II
- Leetcode59 Spiral Matrix II
- leetcode[59]Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode.54(59) Spiral Matrix && II
- 59. Spiral Matrix II
- LeetCode54/59 Spiral Matrix I/II
- 59. Spiral Matrix II
- leetcode59 Spiral Matrix II
- LeetCode59 Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- [59] Spiral Matrix II
- 59. Spiral Matrix II(待进一步研究)
- LeetCode-59-Spiral Matrix II(C语言实现)
- leetcode@ [54/59] Spiral Matrix & Spiral Matrix II