jinhuang1102

54. Spiral Matrix

Nov 29th, 2018
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. class Solution(object):
  2.     def spiralOrder(self, matrix):
  3.         """
  4.        :type matrix: List[List[int]]
  5.        :rtype: List[int]
  6.        """
  7.         res = []
  8.        
  9.         if not matrix:
  10.             return res
  11.        
  12.         rBegin = 0
  13.         rEnd = len(matrix)-1
  14.         cBegin = 0
  15.         cEnd = len(matrix[0])-1
  16.        
  17.         while rBegin <= rEnd and cBegin <= cEnd:
  18.             # traversal right
  19.             for i in range(cBegin, cEnd+1):
  20.                 res.append(matrix[rBegin][i])
  21.             rBegin += 1
  22.            
  23.             # traversal down
  24.             for i in range(rBegin, rEnd+1):
  25.                 res.append(matrix[i][cEnd])
  26.             cEnd -= 1
  27.            
  28.             # traversal left
  29.             if rBegin <= rEnd:
  30.                 for i in range(cEnd, cBegin-1, -1):
  31.                     res.append(matrix[rEnd][i])
  32.             rEnd -= 1
  33.                    
  34.             # traversal up
  35.             if cBegin <= cEnd:
  36.                 for i in range(rEnd, rBegin-1, -1):
  37.                     res.append(matrix[i][cBegin])
  38.             cBegin += 1
  39.            
  40.         return res
Advertisement
Add Comment
Please, Sign In to add comment