leetcode -- Spiral Matrix I&II -- 简单,但需要优化

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

已经写过post

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

对于Spiral Matrix II, 这里我们只需要首先建立一个n*n的matrix,然后像I一样遍历即可。

http://www.cnblogs.com/zuoyuan/p/3769892.html 有更好的方案

上code

class Solution(object):
    def generateMatrix(self, n):
        """ :type n: int :rtype: List[List[int]] """
        if n == 0: return []
        m, n = n, n
        matrix = [[0]*n for x in range(n)]

        i,j = 0, 0
        count = 0
        val = 1
        while i < m and j < n and matrix[i][j] == 0:
            start_i, start_j = i, j
            end_i, end_j = m - count - 1, n - count - 1

            if i == end_i:
                for k in xrange(start_j, end_j + 1):
                    matrix[i][k] = val
                    val += 1
                break
            if j == end_j:
                for k in xrange(start_i, end_i + 1):
                    matrix[i][k] = val
                    val += 1
                break

            while j<=end_j:
                matrix[i][j] = val
                val += 1
                j += 1
            j -= 1
            i += 1
            while i<=end_i:
                matrix[i][j] = val
                val += 1
                i += 1
            i -= 1
            j -= 1
            while j>=start_j:
                matrix[i][j] = val
                val += 1
                j -= 1
            j += 1
            i -= 1
            while  i>start_i:#exclude the mat[i][j]

                matrix[i][j] = val
                val += 1
                i -= 1

            i, j = i + 1, j + 1
            count += 1
        return matrix

你可能感兴趣的:(LeetCode)