标签:
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的情况
下面附上代码,哎刚做了上一题,这道题居然也能做个40分钟,只能说明效率太低,不注意细节了
public class Solution {
public int[][] generateMatrix(int n) {
int number = n*n;
int count = 0;
int[][] matrixResult = new int[n][n];
int rowNumber = 0;
int columnNumber = 0;
while(n>0){
if(n==1){
matrixResult[rowNumber][columnNumber] = ++count;
}
for(int i =0;i<n-1;i++){
matrixResult[rowNumber][columnNumber++] = ++count;
}
for(int i = 0;i<n-1;i++){
matrixResult[rowNumber++][columnNumber]= ++count;
}
for(int i = 0;i<n-1;i++){
matrixResult[rowNumber][columnNumber--]= ++count;
}
for(int i = 0;i<n-1;i++){
matrixResult[rowNumber--][columnNumber]= ++count;
}
rowNumber++;
columnNumber++;
n = n -2;
}
return matrixResult;
}
}
标签:
原文地址:http://www.cnblogs.com/gracyandjohn/p/4399627.html