螺旋矩阵II

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

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

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

建立top,bottom,left,right四个边界,创建n*n二维数组并逆时针赋值,当到达边界时,上、左边界自增,右、下边界自减,当top>bottom或left>right时,结束循环。代码如下:

    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int top = 0;
        int bottom = n-1;
        int left = 0;
        int right = n-1;
        int target = 1;
        //看了一下题解,有的大佬把判断循环是否结束的语句设置为target<=n*n
        while(top <= bottom || left <= right)
        {
            //从左往右
            for(int i = left; i <= right; i++)
            {
                res[top][i] = target++;
            }
            top++;
            //从上往下
            for(int i = top; i <= bottom; i++)
            {
                res[i][right] = target++;
            }
            right--;
            //从右往左
            for(int i = right; i >= left; i--)
            {
                res[bottom][i] = target++;
            }
            bottom--;
            //从下往上
            for(int i = bottom; i >= top; i--)
            {
                res[i][left] = target++;
            }
            left++;
            
        }
        return res;
    }

猜你喜欢

转载自www.cnblogs.com/WakingShaw/p/11581254.html