Hand-torn leecode python:59. Spiral matrix II

Disclaimer: For personal learning purposes, limited capacity, for reference only.

Leek 59: Spiral Matrix 

One, ideas:

The first reaction is a violent solution, using a for loop to solve it.

Try it and feel dizzy,

After checking the information, it is essentially to examine the ability to master the code.

Simulate the process of drawing a matrix clockwise:

1. Uplink from left to right

2. Right column from top to bottom

3. Downstream from right to left

4. Left column from bottom to top.

At first, it was surrounded by the example of N=3. It is recommended to draw an example of N=5 by yourself, which is more convenient to understand----------Here I emphasize that after each clockwise drawing, the initial point x, y needs to be +1, and the initial point needs to be changed this operation.

This understanding is introduced here.

This means that whenever a corner is encountered, the point at the corner is drawn for the new side.

In terms of translation, this is a left-closed-right-open rule[,)

 the code

#螺旋矩阵
#
def generate_matrix(n):
    nums = [[0] * n for _ in range(n)]
    startx, starty =0, 0                          #起始点
    loop, mid = n//2, n//2                        #迭代次数,n为奇数时,矩阵的中心点
    count = 1                                     #计数

    for offset in range(1, loop + 1):             #每循环一层偏移量加1,偏移量从1开始
        for i in range(starty, n - offset):       #从左至右,左闭右开
            nums[startx][i] = count
            count += 1
        for i in range(startx, n - offset):       #从上至下
            nums[i][n - offset] = count
            count += 1 
        for i in range(n - offset, starty, -1):   #从右至左
            nums[n - offset][i] = count
            count += 1
        for i in range(n - offset, startx, -1):   #从下至上
            nums[i][starty] = count
            count += 1
        startx += 1
        starty += 1
    
    if n % 2 !=0:                                 #n为奇数时,填充中心点
        nums[mid][mid] = count
    return nums

Write on the back:

If I were the interviewer, I would ask you, what about printing counterclockwise? Talk about your thoughts.

Guess you like

Origin blog.csdn.net/qq_33083551/article/details/125747680