您的位置:首页 > 编程语言 > Java开发

(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 = 
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Array