Python solution with detailed explanation


  • 0
    G

    Solution

    Spiral Matrix II https://leetcode.com/problems/spiral-matrix-ii/

    Algorithm

    1. The concept is very similar to Spiral Matrix 1. https://discuss.leetcode.com/topic/76331/python-solution-with-detailed-explanation
    2. Use four variables to fill the matrix and adjust them accordingly.
    class Solution(object):
        def generateMatrix(self, n):
            """
            :type n: int
            :rtype: List[List[int]]
            """
            matrix = [[None]*n for _ in range(n)]
            rs,re,cs,ce = 0,n-1,0,n-1
            count = 1
            while rs <= re and cs <= ce:
                for j in range(cs, ce+1):
                    matrix[rs][j], count = count, count+1
                for i in range(rs+1, re+1):
                    matrix[i][ce], count = count, count+1
                for j in range(ce-1, cs-1, -1):
                    matrix[re][j], count = count, count+1
                for i in range(re-1,rs,-1):
                    matrix[i][cs], count = count, count+1
                rs, re = rs+1,re-1
                cs,ce = cs+1,ce-1
            return matrix
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.