Original title:
Given a positive integer n, we generate a square matrix containing all the elements from 1 to n2, and the elements are arranged in a clockwise order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Source: LeetCode
Link: https://leetcode-cn.com/problems/spiral-matrix-ii
Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1:
Idea: Similar to peeling onions, it needs to be filled clockwise layer by layer.
Procedure 1:
First, the first layer is filled when temp = 1, then the second layer is filled when temp = 2, layer by layer. At the same time, the spiral matrix of 54 can also be traversed by this method.
** I think the most clever part of this program is the use of temp to control the number of layers traversed. * *
class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ temp = 1 start = 0 mat = [[0 for _ in range(n)] for _ in range(n)] while temp <= n: for i in range(temp-1, n - temp+1): # left to right start += 1 mat[temp-1][i] = start for i in range(temp, n - temp + 1): # top to bottom start += 1 mat[i][n-temp] = start for i in range(n - temp -1 , temp-2, -1): # right to left start += 1 mat[n-temp][i] = start for i in range(n - temp - 1, temp-1, -1): # bottom to top start += 1 mat[i][temp-1] = start temp += 1 return mat
Procedure two:
Thought: It is also a step-by-step traversal, but the implementation method of the program is to use four variables for boundary control, which is different from the previous program using only one temp variable.
class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[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