JZ19 顺时针打印矩阵
可以将矩阵看成若干层,首先打印最外层的元素,其次打印次外层的元素,直到打印最内层的元素。
对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于 (top,left),右下角位于(bottom,right),按照如下顺序遍历当前层的元素。
1、从左到右遍历上侧元素,依次为(top,left) 到(top,right)。
2、从上到下遍历右侧元素,依次为(top+1,right) 到 (bottom,right)。
3、如果 left<right 且top<bottom,则从右到左遍历下侧元素,依次为(bottom,right−1) 到 (bottom,left+1),以及从下到上遍历左侧元素,依次为(bottom,left) 到(top+1,left)。
遍历完当前层的元素之后,将left 和top 分别增加 1,将 right 和 bottom 分别减少 11,进入下一层继续遍历,直到遍历完所有元素为止。
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
if not matrix:
return
top = 0
left = 0
bottom = len(matrix)-1
right = len(matrix[0])-1
count = len(matrix)*len(matrix[0])
ret = []
while count:
# 左->右
for i in range(left, right+1):
ret.append(matrix[top][i])
count -= 1
if not count:
break
# 上->下
for i in range(top+1, bottom+1):
ret.append(matrix[i][right])
count -= 1
if not count:
break
# 右->左
for i in range(right-1, left-1, -1):
ret.append(matrix[bottom][i])
count -= 1
if not count:
break
# 下->上
for i in range(bottom-1, top, -1):
ret.append(matrix[i][left])
count -= 1
if not count:
break
top += 1
right -= 1
bottom -= 1
left += 1
return ret
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
if not matrix:
return
top = 0
left = 0
bottom = len(matrix)-1
right = len(matrix[0])-1
ret = []
while True:
# 左->右
for i in range(left, right+1):
ret.append(matrix[top][i])
top += 1
if top > bottom:
break
# 上->下
for i in range(top, bottom+1):
ret.append(matrix[i][right])
right -= 1
if right < left:
break
# 右->左
for i in range(right, left-1, -1):
ret.append(matrix[bottom][i])
bottom -= 1
if bottom < top:
break
# 下->上
for i in range(bottom, top-1, -1):
ret.append(matrix[i][left])
left += 1
if left > right:
break
return ret
矩阵可由左上和右下两个坐标确定