[LeetCode]题解(python):059-Spiral Matrix II


题目来源


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.


题意分析


Input: n:integer

Output:a matrix decribed as list[list[]]

Conditions:输入一个大小,得到一个方形矩阵,然后形成蛇形矩阵


题目思路


本题与54题属于一个类别,都是蛇形遍历,这里直接先生成一个初始化的matrix,然后遍历一遍,利用累加变量来赋值


AC代码(Python)


__author__ = 'YE'

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if n == 0:
            return []
        matrix = []
        for i in range(n):
            l = [0 for j in range(n)]
            matrix.append(l)

        up = 0
        left = 0
        down = len(matrix) - 1
        right = len(matrix[0]) - 1

        direct = 0

        res = []

        count = 1

        while True:
            if direct == 0:
                for i in range(left, right + 1):
                    matrix[up][i] = count
                    count += 1
                up += 1
            if direct == 1:
                for i in range(up, down + 1):
                    matrix[i][right] = count
                    count += 1
                right -= 1
            if direct == 2:
                for i in range(right, left - 1, -1):
                    matrix[down][i] = count
                    count += 1
                down -= 1
            if direct == 3:
                for i in range(down, up -1, -1):
                    matrix[i][left] = count
                    count += 1
                left += 1
            if up > down or  left > right:
                return matrix
            direct = (direct + 1) % 4

print(Solution().generateMatrix(3))

 

posted @ 2015-12-28 16:33  loadofleaf  Views(321)  Comments(0Edit  收藏  举报