Leetcode 第59题:Spiral Matrix II--螺旋矩阵II(C++、Python)

题目地址:Spiral Matrix II


题目简介:

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

Example:

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

题目解析:

暴力法:每次都是先向右走,只要能走就走到头,每走一个位置,停下来给当前位置赋值,,然后判断是否可以往下,往左往上。

今日份学习点:给二维vector初始化大小

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int x = 0, y = 0;
        vector<vector<int>> ans(n, vector<int>(n, 0));
        int i = 1;
        while(!ans[y][x])
        {
            ans[y][x] = i++;
            while (x + 1 < n && !ans[y][x + 1])
            {
                x++;
                ans[y][x] = i++;
            }
            while(y + 1 < n && !ans[y + 1][x])
            {
                y++;
                ans[y][x] = i++;
            }
            while (x > 0 && !ans[y][x - 1])
            {
                x--;
                ans[y][x] = i++;
            }
            while(y > 0 && !ans[y - 1][x])
            {
                y--;
                ans[y][x] = i++;
            }
            if(x + 1 < n)
                x++;
        }
        return ans;
    }
};

Python版:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        ans = [[0 for col in range(n)] for row in range(n)]
        i = 1
        x = y = 0
        while(ans[y][x] == 0):
            ans[y][x] = i
            i += 1
            while (x + 1 < n and not ans[y][x + 1]):
                x += 1
                ans[y][x] = i
                i += 1
            while(y + 1 < n and not ans[y + 1][x]):
                y += 1
                ans[y][x] = i
                i += 1
            while (x > 0 and not ans[y][x - 1]):
                x -= 1
                ans[y][x] = i
                i += 1
            while(y > 0 and not ans[y - 1][x]):
                y -= 1
                ans[y][x] = i
                i += 1
            if(x + 1 < n):
                x += 1
        return ans

猜你喜欢

转载自blog.csdn.net/chao_shine/article/details/89131668