DAY 29
0
AI & Data

## 找LeetCode上簡單的題目來撐過30天啦(DAY29)

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心得

### 1 則留言

0

iT邦新手 2 級 ‧ 2021-10-14 21:28:03

soft_soft iT邦新手 5 級 ‧ 2021-10-15 00:25:15 檢舉