Spiral Matrix
一样是一个旋转矩阵的题目,但是注意这个题的维度是n * m而不是n * n,这就意味着会出现外圈完了之后剩下一条横线或者竖线抑或是单个中心点还没有加入进去的情况,这种情况我们都要做单独处理,下面是代码
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
n = len(matrix)
if not n:
return []
m = len(matrix[0])
if not m:
return []
res = []
left, up = 0, 0
right, bottom = m - 1, n - 1
while left < right and up < bottom:
for i in xrange(left, right):
res.append(matrix[up][i])
for i in xrange(up, bottom):
res.append(matrix[i][right])
for i in xrange(right, left, -1):
res.append(matrix[bottom][i])
for i in xrange(bottom, up, -1):
res.append(matrix[i][left])
left += 1
right -= 1
up += 1
bottom -= 1
if left == right and up == bottom:
return res + [matrix[up][left]]
if left == right:
for i in xrange(up, bottom + 1):
res.append(matrix[i][left])
return res
if up == bottom:
for i in xrange(left, right + 1):
res.append(matrix[up][i])
return res
return res
Spiral Matrix II
旋转,跳跃,我闭着眼_(:зゝ∠)_
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res = [[0] * n for _ in xrange(n)]
left, up = 0, 0
right, bottom = n - 1, n - 1
counter = 1
while left < right and up < bottom:
for i in xrange(left, right):
res[up][i] = counter
counter += 1
for i in xrange(up, bottom):
res[i][right] = counter
counter += 1
for i in xrange(right, left, -1):
res[bottom][i] = counter
counter += 1
for i in xrange(bottom, up, -1):
res[i][left] = counter
counter += 1
left += 1
right -= 1
up += 1
bottom -= 1
if left == right and up == bottom:
res[up][left] = counter
return res