题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
数据范围
矩阵中元素数量 [0,400][0,400]。
样例
输入:
[ [1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
解析
直接模拟,遇到边界或已经遍历过的元素时,就顺时针改变方向
代码
Python
class Solution(object):
def printMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
ans = []
if len(matrix) == 0 or len(matrix[0]) == 0:
return ans
n, m = len(matrix), len(matrix[0])
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
st = [[False for _ in range(m)] for _ in range(n)]
x = 0
y = 0
d = 1
for i in range(n * m):
ans.append(matrix[x][y])
st[x][y] = True
a = x + dx[d]
b = y + dy[d]
if a < 0 or a >= n or b < 0 or b >= m or st[a][b]:
d = (d + 1) % 4
a = x + dx[d]
b = y + dy[d]
x = a
y = b
# for i in range(len(st)):
# print(st[i])
# print()
return ans
GO
func printMatrix(matrix [][]int) []int {
ans := []int{}
if len(matrix) == 0 || len(matrix[0]) == 0 {
return ans
}
n, m := len(matrix), len(matrix[0])
st := make([][]bool, n)
for i := 0; i < n; i ++ {
st[i] = make([]bool, m)
}
dx, dy := []int{-1, 0, 1, 0}, []int{0, 1, 0, -1}
x, y, d := 0, 0, 1
for k := 0; k < n * m; k ++ {
ans = append(ans, matrix[x][y])
st[x][y] = true
a, b := x + dx[d], y + dy[d]
if a < 0 || a >= n || b < 0 || b >= m || st[a][b] {
d = (d + 1) % 4;
a, b = x + dx[d], y + dy[d]
}
x, y = a, b
}
return ans
}