59. 螺旋矩阵 II

138 阅读1分钟

IMG_40A11F63D51A-1.jpeg

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int left = 0, up = 0, right = n - 1, bottom = n - 1;
        int total = n * n;
        int count = 1;
        while (count <= total) {
            //从左到右
            for (int i = left; i <= right; i++) {
                res[up][i] = count;
                count++;
            }
            //从上到下
            for (int i = up + 1; i < bottom; i++) {
                res[i][right] = count;
                count++;
            }
            //从右到左,只剩中心时,需要避免重复
            for (int i = right; i >= left && left != right; i--) {
                res[bottom][i] = count;
                count++;
            }
            // 从下到上
            for (int i = bottom - 1; i > up; i--) {//
                res[i][left] = count;
                count++;
            }
            left++;
            right--;
            up++;
            bottom--;
        }
        return res;
    }
}