Spiral Matrix
Problem: Spiral Matrix
The general idea is to set boundary for us and keep going until meet bound then we turn right and modify bounds.
Code in Python:
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix: return []
up, down, left, right = 0, len(matrix), -1, len(matrix[0])
ans = []
direction = 1
while left < right and up < down:
if direction == 1:
for i in xrange(left+1, right):
ans.append(matrix[up][i])
direction = 2
right -= 1
continue
if direction == 2:
for i in xrange(up+1, down):
ans.append(matrix[i][right])
direction = 3
down -= 1
continue
if direction == 3:
for i in xrange(right-1, left, -1):
ans.append(matrix[down][i])
direction = 4
left += 1
continue
if direction == 4:
for i in xrange(down-1, up, -1):
ans.append(matrix[i][left])
direction = 1
up += 1
continue
return ans
There's a cooler solution use a number to mark which round we are running.