題號:59 標題:Spiral Matrix II 難度:Medium
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
• 1 <= n <= 20
我的程式碼
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int i=0,j=0,k=1,ax=0,ay=0,bx=0,by=n-1,cx=n-1,cy=n-1,dx=n-1,dy=0;
while(k!=(n*n+1)){
for(i=ay;i<=by;i++){
System.out.print(" 1:" + k);
result[ax][i] = k;
k++;
}
ax++;
bx++;
for(i=bx;i<=cx;i++){
System.out.print(" 2:" + k);
result[i][by] = k;
k++;
}
by--;
cy--;
for(i=cy;i>=dy;i--){
System.out.print(" 3:" + k);
result[cx][i] = k;
k++;
}
cx--;
dx--;
for(i=dx;i>=ax;i--){
System.out.print(" 4:" + k);
result[i][dy] = k;
k++;
}
dy++;
ay++;
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
//System.out.print(result[i][j]);
}
}
return result;
}
}
day29心得
陣列越寫越順了呢,開心,明天就要結束拉,開心