Leetcode-Spiral Matrix II Spiral Matrix 2 python method is good, just get it in four lines. Do you believe it ?, Leetcodepython

Source: Internet
Author: User

Leetcode-Spiral Matrix II Spiral Matrix 2 python method is good, just get it in four lines. Do you believe it ?, Leetcodepython

Spiral Matrix II

 

Spiral Matrix

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

For example,
Given n = 3,

You should return the following matrix:

[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

 

I was dizzy after reading a long story when I encountered this problem during an interview at the blog Park. I ran to the leetcode discussion area. It seems that I am still awesome with python, And you can believe it in four lines ..

| 1 | 2 | 3 |

| 8 | 9 | 4 |

| 7 6 | 5 |

If you do not understand it, the general process is like the above. The same color indicates that the process is executed in the same step.

 

>>> Def generateMatrix (n ):... a, low = [], n * n + 1... while low> 1 :... low, high = low-len (A), low... A = [list (range (low, high)] + list (zip (* A [:-1]) # The python3.3 syntax is different from that of 2.7... print ()... return A...> generateMatrix (1) [[] [[1] [[1]> generateMatrix (2) [[[] [[4] [[3], (4,)] [[1, 2], (4, 3)] [[1, 2], (4, 3)] >>> generateMatrix (3) [[] [9] [[8], (9,)] [6, 7], (9, 8)] [[4, 5], (9, 6), (8, 7)] [[1, 2, 3], (8, 9, 4), (7, 6, 5)] [[1, 2, 3], (8, 9, 4), (7, 6, 5)]

 

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.