当前位置:网站首页>59. Spiral matrix

59. Spiral matrix

2022-07-06 05:27:00 365JHWZGo

List of articles

subject

''' Description: 59. Spiral matrix  Autor: 365JHWZGo Date: 2022-02-12 20:50:58 LastEditors: 365JHWZGo LastEditTime: 2022-02-12 21:06:35 '''

Ideas

I think it's a spiral to get the answer , There is no real solution , Just solve it directly by violence , That is, the results are obtained in order .
 Insert picture description here
When n=10 Schematic answer when

[[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10], 
 [36, 37, 38, 39, 40, 41, 42, 43, 44, 11], 
 [35, 64, 65, 66, 67, 68, 69, 70, 45, 12], 
 [34, 63, 84, 85, 86, 87, 88, 71, 46, 13], 
 [33, 62, 83, 96, 97, 98, 89, 72, 47, 14], 
 [32, 61, 82, 95, 100, 99, 90, 73, 48, 15], 
 [31, 60, 81, 94, 93, 92, 91, 74, 49, 16], 
 [30, 59, 80, 79, 78, 77, 76, 75, 50, 17], 
 [29, 58, 57, 56, 55, 54, 53, 52, 51, 18], 
 [28, 27, 26, 25, 24, 23, 22, 21, 20, 19]]

Code

class Solution(object):
    def generateMatrix(self, n):
        """ :type n: int :rtype: List[List[int]] """
        if n == 1:
            return [[1]]
        if n == 2:
            return [[1,2],[4,3]]
        demo = [[i+1 for i in range(n)]for _ in range(n)]
        # print(demo)
        final = n**2    #  The target 
        num = n+1       #  The number 
        i,j = 0,n-1     #  Subscript 
        time = 1
        U,D,L,R = n-time-1,n-time,n-time-1,n-time
        while num<=final:
            if R:
                i+=1
                demo[i][j] = num
                R-=1
                num+=1
            elif D:
                j-=1
                demo[i][j] = num
                D-=1
                num+=1
            elif L:
                i-=1
                demo[i][j] = num
                L-=1
                num+=1
            elif U:
                j+=1
                demo[i][j] = num
                U-=1
                num+=1
            else:
                time+=2
                U,D,L,R = n-time-1,n-time,n-time-1,n-time
            
        return demo

 Insert picture description here

原网站

版权声明
本文为[365JHWZGo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132106100684.html