力扣每日一题 59 螺旋矩阵

力扣每日一题 59 螺旋矩阵

题目

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
力扣每日一题 59 螺旋矩阵_第1张图片
思路:
力扣每日一题 59 螺旋矩阵_第2张图片

C++:

 class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int num = 1;	//初始值
        int left = 0, top = 0, right = n - 1, bottom = n - 1;	//定义上下左右边界

        //初始化数组
        vector<vector<int>> res(n,vector<int>(n));
        while (num <= n*n ) {	//开始4个for循环,模拟转一圈

            //left to right从左到右的过程,全部是左开右闭
            for (int i = left; i <= right; ++i) res[top][i] = num++;
            ++top;

            //top to bottom
            for (int i = top; i <= bottom; ++i) res[i][right] = num++;
            --right;

            //right to left
            for (int i = right; i >= left; --i) res[bottom][i] = num++;
            --bottom;

            //bottom to top
            for (int i = bottom; i >= top; --i) res[i][left] = num++;
            ++left;
        }
        return res;
    }
};

Java:

class Solution {
    public int[][] generateMatrix(int n) {
        int l = 0, r = n - 1, t = 0, b = n - 1;
        int[][] mat = new int[n][n];
        int num = 1, tar = n * n;
        while(num <= tar){
            for(int i = l; i <= r; i++) mat[t][i] = num++; // left to right.
            t++;
            for(int i = t; i <= b; i++) mat[i][r] = num++; // top to bottom.
            r--;
            for(int i = r; i >= l; i--) mat[b][i] = num++; // right to left.
            b--;
            for(int i = b; i >= t; i--) mat[i][l] = num++; // bottom to top.
            l++;
        }
        return mat;
    }
}

Python:

class Solution:
    def generateMatrix(self, n: int) -> [[int]]:
        l, r, t, b = 0, n - 1, 0, n - 1
        mat = [[0 for _ in range(n)] for _ in range(n)]
        num, tar = 1, n * n
        while num <= tar:
            for i in range(l, r + 1): # left to right
                mat[t][i] = num
                num += 1
            t += 1
            for i in range(t, b + 1): # top to bottom
                mat[i][r] = num
                num += 1
            r -= 1
            for i in range(r, l - 1, -1): # right to left
                mat[b][i] = num
                num += 1
            b -= 1
            for i in range(b, t - 1, -1): # bottom to top
                mat[i][l] = num
                num += 1
            l += 1
        return mat

你可能感兴趣的:(矩阵,leetcode,算法)