这题难度中等,记录下思路
第一个会超时,
第二个:思想是按斜对角线行进行右下左上交替遍历,
1
def
traverse(matrix):
2
n=len(matrix)-1
3
m=len(matrix[0])-1
4
result=
[]
5
for
i
in
range(m+n+1
):
6
if
(i % 2 ==
0):
7
for
j
in
range(i, -1, -1
):
8
x=
j
9
y=i-
x
10
if
x <= n
and
y <=
m:
11
result.append(matrix[x][y])
12
#
elif y > m:
13
#
break
14
else
:
15
continue
16
else
:
17
for
j
in
range(i, -1, -1
):
18
y=
j
19
x=i-
y
20
if
x <= n
and
y <=
m:
21
result.append(matrix[x][y])
22
#
elif x > n:
23
#
break
24
else
:
25
continue
26
return
result
27
28
if
__name__
==
'
__main__
'
:
29
ma=
[
30
[ 1, 2, 3
],
31
[ 4, 5, 6
],
32
[ 7, 8, 9
]
33
]
34
print
(traverse(ma))
11
1
def
diagonial(matrix):
2
m=
len(matrix)
3
n=
len(matrix[0])
4
#
思想是按斜对角线行进行遍历
5
#
遍历的方向右下,左上交替进行
6
line=
0
7
res=
[]
8
tem=
[]
9
is_sure=
True
10
#
对每一行进行循环 斜对角线有m+n-1条
11
while
line<(m+n-1
):
12
#
设置起点
13
if
(line<
m):
14
x=
line
15
y=
0
16
else
:
17
x=m-1
18
y=line-m-1
19
#
每行循环几次
20
#
因为都是从右上开始,所以设置条件x>0,y
21
while
x>=0
and
y <
n:
22
#
存储斜行的元素
23
tem.append(matrix[x][y])
24
x-=1
25
y+=1
26
#
如果是左下开始,则反向添加
27
if
(is_sure):
28
tem.reverse()
29
for
num
in
tem:
30
res.append(num)
31
line+=1
32
return
res
33
34
35
if
__name__
==
'
__main__
'
:
36
matrix=
[
37
[ 1, 2, 3
],
38
[ 4, 5, 6
],
39
[ 7, 8, 9
]
40
]
41
print
(diagonial(matrix))

