🌕 59. 螺旋矩阵 II

吞佛童子2022年6月9日
  • algorithm
  • array
小于 1 分钟

🌕 59. 螺旋矩阵 II

难度: 🌕

问题描述

img_15.png


解法

class Solution {
    public int[][] generateMatrix(int n) {
        // 思路:
        int[][] res = new int[n][n];
        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;
        int cur = 1;
        while(left <= right && top <= bottom) {
            if(left <= right && top <= bottom) {
                // left -> right
                for(int j = left; j <= right; j ++) {
                    res[top][j] = cur;
                    cur ++;
                }
            }
            top ++;
            if(left <= right && top <= bottom) {
                // top -> bottom
                for(int i = top; i <= bottom; i ++) {
                    res[i][right] = cur;
                    cur ++;
                }
            }
            right --;
            if(left <= right && top <= bottom) {
                // right -> left
                for(int j = right; j >= left; j --) {
                    res[bottom][j] = cur;
                    cur ++;
                }
            }
            bottom --;
            if(left <= right && top <= bottom) {
                // bottom -> top
                for(int i = bottom; i >= top; i --) {
                    res[i][left] = cur;
                    cur ++;
                }
            }
            left ++;
        }
        return res;
    }
}

输出

img_14.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou