halaluddin

Day13-Apr-Spiral_Matrix_II

Apr 14th, 2022 (edited)
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. """
  2.     Problem Link: https://leetcode.com/problems/spiral-matrix-ii/
  3.    Language:
  4.        Python
  5.    Params:
  6.         n: Int
  7.    Return:
  8.         2D intager list
  9.    Complexity Analysis:
  10.        Space: O(nˆ2)
  11.        Time: (nˆ2)
  12.            Outer while loop and inner for loops
  13.            takes (nˆ2) time to execute.
  14. """
  15.  
  16. class Solution:
  17.     def generateMatrix(self, n: int) -> List[List[int]]:
  18.         matrix = []
  19.         for _ in range(n):
  20.             matrix.append([0]*n)
  21.         left, right, up, down = 0, n-1, 0, n-1
  22.         curr_num = 0
  23.         while curr_num < n*n:
  24.  
  25.             for curr_index in range(left, right+1):
  26.                 curr_num += 1
  27.                 matrix[left][curr_index] = curr_num
  28.  
  29.             for curr_index in range(up+1, down+1):
  30.                 curr_num += 1
  31.                 matrix[curr_index][right] = curr_num
  32.  
  33.  
  34.             for curr_index in range(right-1, left-1, -1):
  35.                 curr_num += 1
  36.                 matrix[down][curr_index] = curr_num
  37.  
  38.             for curr_index in range(down-1, up, -1):
  39.                 curr_num += 1
  40.                 matrix[curr_index][left] = curr_num
  41.  
  42.             left += 1
  43.             right -= 1
  44.             up += 1
  45.             down -= 1
  46.  
  47.         return matrix
Add Comment
Please, Sign In to add comment