(Java)LeetCode-59. Spiral Matrix II
2016-10-05 22:21
411 查看
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+1)/2层,每一层按四个方向放完之后,再往里深入一层。代码如下:
下面补充一下我在 https://my.oschina.net/Tsybius2014/blog/525517 看到的代码,思路都是一样的,就是写起来不太一样。
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
这道题和之前那个从矩阵中旋转取数的很相似,这里是旋转着放数。
我的想法是分成(n+1)/2层,每一层按四个方向放完之后,再往里深入一层。代码如下:
public class Solution { public int[][] generateMatrix(int n) { int num = 1; int edgeLen = n; int[][] result = new int ; for(int i = 0; i < (n+1)/2; i++){ for(int j = 0; j < edgeLen; j++){ result[i][i+j] = num ++; } for(int j = 1; j < edgeLen; j++){ result[i+j][i+edgeLen-1] = num ++; } for(int j = edgeLen-2; j >= 0; j--){ result[i+edgeLen-1][i+j] = num ++; } for(int j = edgeLen-2; j >= 1; j--){ result[i+j][i] = num ++; } edgeLen -=2; } return result; } }
下面补充一下我在 https://my.oschina.net/Tsybius2014/blog/525517 看到的代码,思路都是一样的,就是写起来不太一样。
/** * @功能说明:LeetCode 59 - Spiral Matrix II * @开发人员:Tsybius2014 * @开发时间:2015年11月3日 */ public class Solution { /** * 生成矩阵 * @param n * @return */ public int[][] generateMatrix(int n) { if (n < 0) { n = 0; } int[][] matrix = new int ; if (n == 0) { return matrix; } int counter = 1; //左右上下四个边界 int left = 0; int right = matrix[0].length - 1; int top = 0; int bottom = matrix.length - 1; int i; while (true) { //上边,自左至右 for (i = left; i <= right; i++) { matrix[top][i] = counter++; } if (++top > bottom) { break; } //右边,自上至下 for (i = top; i <= bottom; i++) { matrix[i][right] = counter++; } if (left > --right) { break; } //下边,自右至左 for (i = right; i >= left; i--) { matrix[bottom][i] = counter++; } if (top > --bottom) { break; } //左边,自下至上 for (i = bottom; i >= top; i--) { matrix[i][left] = counter++; } if (++left > right) { break; } } return matrix; } }
相关文章推荐
- leetcode-java-59. Spiral Matrix II
- [leetcode-59]spiral matrixII(java)
- LeetCode --- 59. Spiral Matrix II
- [LeetCode 59] Spiral Matrix II
- 【LeetCode】(59)Spiral Matrix II(Medium)
- 【leetcode】【59】Spiral Matrix II
- 59. Spiral Matrix II LeetCode
- Spiral Matrix II leetcode java
- leetcode 59:Spiral Matrix II
- LeetCode-59-Spiral Matrix II(Array)-Medium
- LeetCode(59)SPiral Matrix II
- [Leetcode] Spiral Matrix II (Java)
- LeetCode_59---Spiral Matrix II
- leetcode 59: Spiral Matrix II
- 【leetcode】Array——Spiral MatrixII(59)
- [Leetcode] 59. Spiral Matrix II
- Java for LeetCode 059 Spiral Matrix II
- leetcode JAVA Spiral Matrix II 难度系数3 3.19
- 【LEETCODE】59-Spiral Matrix II
- LeetCode 59. Spiral Matrix II