LeetCode 59. Spiral Matrix II

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,求解出n*n的矩陣,同時填充數字,循環填充。

代碼:

public int[][] generateMatrix(int n) {

        int total = n*n;
        int[][] result= new int[n][n];
     
        int x=0;
        int y=0;
        int step = 0;
     
        for(int i=0;i<total;){
            while(y+step<n){
                i++;
                result[x][y]=i; 
                y++;
     
            }    
            y--;
            x++;
     
            while(x+step<n){
                i++;
                result[x][y]=i;
                x++;
            }
            x--;
            y--;
     
            while(y>=0+step){
                i++;
                result[x][y]=i;
                y--;
            }
            y++;
            x--;
            step++;
     
            while(x>=0+step){
                i++;
                result[x][y]=i;
                x--;
            }
            x++;
            y++;
        }
     
        return result;
    }

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容