c++
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int num = 1;
vector<vector<int>> matrix(n, vector<int>(n));
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
matrix[top][column] = num;
num++;
}
for (int row = top + 1; row <= bottom; row++) {
matrix[row][right] = num;
num++;
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
matrix[bottom][column] = num;
num++;
}
for (int row = bottom; row > top; row--) {
matrix[row][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/spiral-matrix-ii/solution/luo-xuan-ju-zhen-ii-by-leetcode-solution-f7fp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Python
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
rows = n
columns = n
total = n* n
row = 0
column = 0
matrix = [[0] * n for _ in range(n)]
directionindex = 0
for i in range(total):
if n == 0:
return []
matrix[row][column] = i + 1
nextrow = row + direction[directionindex][0]
nextcolumn = column + direction[directionindex][1]
if nextrow < 0 or nextrow >= rows or nextcolumn < 0 or nextcolumn >= columns or matrix[nextrow][nextcolumn] > 0:
directionindex = (directionindex + 1) % 4
row = row + direction[directionindex][0]
column = column + direction[directionindex][1]
return matrix
# class Solution:
# def generateMatrix(self, n: int) -> List[List[int]]:
# dirs = [(0, 1), [1, 0], (0, -1), (-1, 0)]
# matrix = [[0] * n for _ in range(n)]
# row, col, dirIdx = 0, 0, 0
# for i in range(n * n):
# matrix[row][col] = i + 1
# dx, dy = dirs[dirIdx]
# r, c = row + dx, col + dy
# if r < 0 or r >= n or c < 0 or c >= n or matrix[r][c] > 0:
# dirIdx = (dirIdx + 1) % 4 # 顺时针旋转至下一个方向
# dx, dy = dirs[dirIdx]
# row, col = row + dx, col + dy
# return matrix
# 作者:LeetCode-Solution
# 链接:https://leetcode-cn.com/problems/spiral-matrix-ii/solution/luo-xuan-ju-zhen-ii-by-leetcode-solution-f7fp/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
2021.03.16——力扣每日一题_59.螺旋矩阵II