力扣刷题59. 螺旋矩阵 II(java)

英文题目

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
给一个正整数 n 生成一个 矩阵 覆盖 从 1 到 n^2 的 螺旋矩阵

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

解决

承接上题螺旋矩阵

class Solution {
    public int[][] generateMatrix(int n) {
        int [][] ans = new int [n][n];
        int r =0, c = 0,di = 0;;
        int[] dr = {0, 1, 0, -1};
        int[] dc = {1, 0, -1, 0};
        int r0 = 0, r1 = n,c0 = 0,c1 = n;
        int cr ,cc;
        for(int i = 1 ; i <= n*n; i++){
            ans[r][c] = i;
            cr = r + dr[di];
            cc = c + dc[di];
            if (r0 <= cr && cr < r1 && c0 <= cc && cc < c1 ){
                r = cr; // r下一个位置
                c = cc;  // c 下一个位置
            }else{
                di = (di + 1) % 4;
                r += dr[di];
                c += dc[di];
                if(dr[di] ==1 ){
                    r0++;
                }
                if(dr[di] == -1){
                    r1--;
                }
                if(dc[di] == 1){
                    c0++;
                }
                if(dc[di] == -1){
                    c1--;
                }
            }
        }
        return ans;
    }
}

你可能感兴趣的:(力扣腾讯精选50道)