Skip to content

Latest commit

 

History

History
66 lines (56 loc) · 1.55 KB

20200703-螺旋矩阵 II.md

File metadata and controls

66 lines (56 loc) · 1.55 KB

每天一道leetCode

信息卡片

题目描述

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

示例:

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

参考答案

一模一样的

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        if (n < 1) {
            return result;
        }
        int top = 0, left = 0, bottom = n - 1, right = n - 1, x = 1;
        while(top <= bottom && left <= right) {
            for (int col = left; col <= right; col++) {
                result[top][col] = x;
                x++;
            }
            for(int row = top + 1; row <= bottom; row++) {
                result[row][right] = x;
                x++;
            }
            if (top < bottom && left < right) {
                for(int col = right - 1; col >= left; col--) {
                    result[bottom][col] = x;
                    x++;
                }
                for(int row = bottom - 1; row >= top + 1; row--) {
                    result[row][left] = x;
                    x++;
                }
            }
            top++;
            left++;
            bottom--;
            right--;
        }
        return result;
    }
}