JZ29 顺时针打印矩阵

JZ29 顺时针打印矩阵

描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

例如,如果输入如下4 X 4矩阵:

1
2
3
4
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]

则依次打印出数字:

1
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]

数据范围:$0 <= matrix.length <= 100,0 <= matrix[i].length <= 100$

示例1

1
2
输入:[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
返回值:[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]

示例2

1
2
输入:[[1,2,3,1],[4,5,6,1],[4,5,6,1]]
返回值:[1,2,3,1,1,1,6,5,4,4,5,6]

题解

我讨厌模拟。按照题目模拟移动即可,创建访问记录矩阵记录访问过的元素,然后根据边界条件更改移动方向即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# -*- coding:utf-8 -*-
def create_ones_matrix(inputs):
rows = len(inputs)
cols = len(inputs[0]) if rows > 0 else 0

# 创建全1矩阵
ones_matrix = [[1] * cols for _ in range(rows)]
return ones_matrix


class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
if not matrix or not matrix[0]:
return []

usage = create_ones_matrix(matrix)
i, j = 0, 0
res = []

# 定义方向:右、下、左、上
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
dir_idx = 0 # 当前方向索引

for _ in range(len(matrix) * len(matrix[0])):
res.append(matrix[i][j])
usage[i][j] = 0

# 尝试按照当前方向移动
next_i = i + directions[dir_idx][0]
next_j = j + directions[dir_idx][1]

# 如果下一个位置无效,改变方向
if (next_i < 0 or next_i >= len(matrix) or
next_j < 0 or next_j >= len(matrix[0]) or
usage[next_i][next_j] == 0):

dir_idx = (dir_idx + 1) % 4 # 改变方向
next_i = i + directions[dir_idx][0]
next_j = j + directions[dir_idx][1]

i, j = next_i, next_j

return res