LeetCode:蛇形矩阵II(spiral matrix II)

题目:

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 ]
]

思路:

1. 判断特殊情况,n=0或1

2. 定义左右上下边界,依次填充数组;动态更新边界,继续填充,直到左右边界重合或上下边界重合。

3. 注意每次填充的前提是num小于n*n

代码(Python):时间 O(n),  空间 O(n) 

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if n == 0: return []
        if n == 1: return [[1]]
        arr = [[0]*n for i in range(n)]
        row_begin = 0; row_end = n-1; col_begin = 0; col_end = n-1
        num = 1; final = n*n
        while num <= final:
            if num <= final and col_begin < col_end:   
                for i in range(col_begin, col_end+1):
                    arr[row_begin][i] = num
                    num += 1
                row_begin += 1
            if num <= final and row_begin < row_end:
                for i in range(row_begin, row_end+1):
                    arr[i][col_end] = num
                    num += 1
                col_end -= 1
            if num <= final and col_begin < col_end:
                for i in range(col_end, col_begin-1,-1):
                    arr[row_end][i] = num
                    num += 1
                row_end -= 1
            if num <= final and row_begin < row_end: 
                for i in range(row_end, row_begin-1,-1):
                    arr[i][col_begin] = num
                    num += 1
                col_begin += 1
        return arr
简化后的代码:只用两个变量作为边界判断条件。

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if n == 0: return []
        arr = [[0]*n for i in range(n)]
        start = 0; end = n-1; num = 1; final = n*n
        while start < end:
            for j in range(start, end+1):
                arr[start][j] = num
                num += 1
            for i in range(start+1, end+1):
                arr[i][end] = num
                num += 1
            for j in range(end-1, start-1,-1):
                arr[end][j] = num
                num += 1
            for i in range(end-1, start,-1):
                arr[i][start] = num
                num += 1
            start += 1
            end -= 1
        if start == end: arr[start][end]=final
        return arr

你可能感兴趣的:(杂栏:数学&计算机学科知识)