54.Spiral Matrix

class Solution(object): def spiral(self, matrix): """ input: int[][] matrix return: Integer[] """ if (len(matrix)==0): return [] # not a square matrix, so need to examine edge case again elif (len(matrix[0])==0): return [] # write your solution here nrow = len(matrix) ncol = len(matrix[0]) res = [] # every round handle an outer loop upper = 0 lower = nrow-1 left = 0 right = ncol-1 # inclusive while(True): # 1. print the upper boundary for c in range(left,right+1): res.append(matrix[upper][c]) upper += 1 if (upper > lower): break # 2. print the right boundary for r in range(upper, lower+1): res.append(matrix[r][right]) right -= 1 if (right < left): break # 3. print the lower boundary for c in range(right, left-1, -1): res.append(matrix[lower][c]) lower -= 1 if (upper > lower): break # 4. print the left boundary for r in range(lower, upper-1, -1): res.append(matrix[r][left]) left += 1 if (right < left): break return res
Note the empty case here.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.