iT邦幫忙

2021 iThome 鐵人賽

DAY 29
0
AI & Data

想到甚麼打甚麼系列 第 29

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

  • 分享至 

  • xImage
  •  

題號: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心得
陣列越寫越順了呢,開心,明天就要結束拉,開心


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY28)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY30)
系列文
想到甚麼打甚麼30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
阿瑜
iT邦研究生 4 級 ‧ 2021-10-14 21:28:03

期待明天 完賽文!

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

我已PO,超糞XDDDDD

我要留言

立即登入留言