当前位置:网站首页>[leetcode] 103 spiral matrix II

[leetcode] 103 spiral matrix II

2020-12-08 12:50:22 JaneRoad

subject :

image-20201208123945905

image-20201208124017502

Their thinking :

image-20201208123552689

https://leetcode-cn.com/problems/spiral-matrix-ii/solution/spiral-matrix-ii-mo-ni-fa-she-ding-bian-jie-qing-x/

Code :

public class LC91 {

    public 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;
    }

    public static void main(String[] args) {
        LC91 lc91 = new LC91();
        int[][] arr = lc91.generateMatrix(3);
        for (int i = 0; i < arr.length; i++) {
            for (int i1 = 0; i1 < arr[0].length; i1++) {
                System.out.println(arr[i][i1]);
            }

        }
    }
}

版权声明
本文为[JaneRoad]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201208124939153o.html