LeetCode算法题:螺旋矩阵 II generateMatrix

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:类似螺旋矩阵,一圈一圈。

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


        int[][] res = new int[n][n];

        int step = n * n;
        int cur = 0, i = 0, j = 0;
        int ii = 0, jj = 0;
        int jLength = n;
        int iLength = n;
        while (cur < step) {
            if (cur > 0) {
                jLength -= 1;
                iLength -= 1;
                ii += 1;
                jj += 1;
            }
            while (cur < step && j < jLength)res[i][j++]=++cur;
            j--;
            i++;
            while (cur < step && i < iLength)res[i++][j]=++cur;
            i--;
            j--;
            while (cur < step && j >= jj)res[i][j--]= ++cur;
            j++;
            i--;
            while (cur < step && i > ii)res[i--][j]=++cur;
            i++;
            j++;
        }
        return res;

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

    }
}

你可能感兴趣的:(LeetCode)