Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
给出一个数字n,让输出一个二维数组,元素是从1~n2,而且要是螺旋方式
思路:
从1~n2很简单,主要是螺旋方式,螺旋方式可以参考54题,还是两条边两条边地输出,先是第一行和最后一列,然后
迂回最后一行和第一列,如此循环。
注意每个while (row <= endRow && col <= endCol) {结束时,row都是多一行或者少一行的,
而且为了避免位置重复,列也是要+1或者-1
//0ms
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int element = 1;
int lastE = n * n;
int startRow = 0;
int endRow = n - 1;
int startCol = 0;
int endCol = n - 1;
int row = startRow;
int col = startCol;
while (element <= lastE) {
while (row <= endRow && col <= endCol) {
result[row][col] = element;
if (col == endCol) {
row ++;
} else {
col ++;
}
element ++;
}
row --;
col --;
startRow ++;
endCol --;
while (row >= startRow && col >= startCol) {
result[row][col] = element;
if (col == startCol) {
row --;
} else {
col --;
}
element ++;
}
row ++;
col ++;
endRow --;
startCol ++;
}
return result;
}
另一版本
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int sR = 0;
int eR = n - 1;
int sC = 0;
int eC = n - 1;
int row = 0;
int col = 0;
int i = 1;
while(sR <= eR) {
if(row == sR) {
while(col <= eC) {
res[row][col] = i ++;
col ++;
}
col = eC;
row ++;
while(row <= eR) {
res[row][col] = i ++;
row ++;
}
row = eR;
col --;
sR ++;
eC --;
}
if(row == eR) {
while(col >= sC) {
res[row][col] = i ++;
col --;
}
col = sC;
row --;
while(row >= sR) {
res[row][col] = i ++;
row --;
}
row = sR;
col ++;
eR --;
sC ++;
}
}
return res;
}
3
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int cnt = 1;
int minR = 0;
int maxR = n-1;
int minC = 0;
int maxC = n-1;
int r = 0;
int c = 0;
while(minR <= maxR && minC <= maxC) {
if(minR <= maxR && minC <= maxC) {
while(c <= maxC) {
res[r][c] = cnt++;
c ++;
}
c = maxC;
minR ++;
r = minR;
while(r <= maxR){
res[r][c] = cnt++;
r++;
}
r = maxR;
maxC--;
c = maxC;
}
if(minR <= maxR && minC <= maxC) {
while(c >= minC) {
res[r][c] = cnt++;
c --;
}
c = minC;
maxR --;
r = maxR;
while(r >= minR){
res[r][c] = cnt++;
r--;
}
r = minR;
minC++;
c = minC;
}
}
return res;
}