当前位置:网站首页>【LeetCode】59. Spiral matrix II

【LeetCode】59. Spiral matrix II

2022-06-26 10:09:00 later_ rql

1. Title Description

Give you a positive integer n , Generate a include 1 To n2 All the elements , And the elements are arranged in a clockwise spiral order n x n square matrix matrix .
 Insert picture description here

2. Their thinking

Ideas : There are four assignment processes
From left to right l_r
From top to bottom u_d
From right to left r_l
From bottom to top d_u
x Record the left and right of each lap , Up and down the border
y Record the right and left of each lap , Lower and upper boundary
x,y As the circle shrinks , Change accordingly ,x–,y++,
Finally, consider n Strange situation x==y, by arr[x][y] assignment n
n
n Don't think about it for me .**

3. Code

Code 1 : His writing , Some redundancy .

 public static int[][] generateMatrix(int n) {
    
        int[][] arr=new int[n][n];
        int l_r,u_d,r_l,d_u,index;
        l_r=0;
        r_l=n-1;
        u_d=0;
        d_u=n-1;
        index=1;
        int x=n-1;// Number of columns 
        int y=0;// Row number 
        while (index<Math.pow(n,2)) {
    
            // From left to right 
            while (l_r < x) {
    
                arr[u_d][l_r] = index;
                index++;
                l_r++;
            }
            // From top to bottom 
            while (u_d < x) {
    
                arr[u_d][l_r] = index;
                index++;
                u_d++;
            }
            // From right to left 
            while (r_l > y) {
    
                arr[u_d][r_l] = index;
                index++;
                r_l--;
            }
            // From bottom to top 
            while (d_u > y) {
    
                arr[d_u][r_l] = index;
                index++;
                d_u--;
            }
            // After each lap , Narrow the scope 
            x--;
            y++;
            l_r = y;
            r_l = x;
            u_d = y;
            d_u = x;
        }
        if (x==y){
    
            arr[x][y]=n * n;
        }
        return arr;

    }

Code 2 : Written by pen pal , Very concise , Understandability .

 public static int[][] generateMatrix(int n) {
    
        int l = 0, r = n - 1, t = 0, b = n - 1;
        int[][] mat = new int[n][n];
        int num = 1, tar = n * n;
        while(num <= tar){
    
            for(int i = l; i <= r; i++) mat[t][i] = num++; // left to right.
            t++;
            for(int i = t; i <= b; i++) mat[i][r] = num++; // top to bottom.
            r--;
            for(int i = r; i >= l; i--) mat[b][i] = num++; // right to left.
            b--;
            for(int i = b; i >= t; i--) mat[i][l] = num++; // bottom to top.
            l++;
        }
        return mat;
    }

source : Power button (LeetCode)
link :link-59. Spiral matrix II

原网站

版权声明
本文为[later_ rql]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260921254371.html