[Leetcode] (python): 059-spiral Matrix II

Source: Internet
Author: User

Source of the topic

https://leetcode.com/problems/spiral-matrix-ii/

Given an integer n, generate a square matrix filled with elements from 1 to n2 in Spiral order.

Test instructions Analysis

Input:n:integer

Output:a matrix decribed as list[list[]

Conditions: Enter a size, get a square matrix, and then form a serpentine matrix

Topic ideas

The topic and 54 belong to a category, are serpentine traversal, where the direct Mr. into an initialized matrix, and then iterate over, using the cumulative variable to assign value

AC Code (PYTHON)

__author__='YE'classsolution (object):defGeneratematrix (self, n):""": Type N:int:rtype:list[list[int]]"""        ifn = =0:return[] Matrix= []         forIinchrange (N): l= [0 forJinchrange (n)] Matrix.append (l) up=0 Left=0 Down= Len (Matrix)-1 Right= Len (matrix[0])-1Direct=0 Res=[] Count= 1 whileTrue:ifDirect = =0: forIinchRange (left, right + 1): Matrix[up][i]=Count Count+ = 1 up+ = 1ifDirect = = 1:                 forIinchRange (up, down + 1): Matrix[i][right]=Count Count+ = 1 Right-= 1ifDirect = = 2:                 forIinchRange (right, left-1, 1): Matrix[down][i]=Count Count+ = 1 Down-= 1ifDirect = = 3:                 forIinchRange (down, up-1, 1): Matrix[i][left]=Count Count+ = 1 Left+ = 1ifUp > DownorLeft >Right :returnMatrix Direct= (direct + 1)% 4Print(Solution (). Generatematrix (3))

[Leetcode] (python): 059-spiral Matrix II

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.