# Python clear thinking iterative

• ``````class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
elif len(matrix[0]) == 1:
return [matrix[i][0] for i in range(len(matrix))]
elif len(matrix) == 1:
return matrix[0]
length = len(matrix) * len(matrix[0])
print(length)
visited = [[False for j in range(len(matrix[i]))] for i in range(len(matrix))]
data = []
# self.helper("up", 0, 0, matrix, visited, length, data)
r = c = 0
dir = "up"
while len(data) != length:
visited[r][c] = True
data.append(matrix[r][c])
if dir == "up":
if r == 0 or c == len(matrix[r]) - 1:
if c + 1 < len(matrix[r]) and visited[r][c + 1] is False:
dir = "down"
c += 1
elif r + 1 < len(matrix) and visited[r + 1][c] is False:
dir = "down"
r += 1
else:
if r - 1 >= 0 and visited[r - 1][c] is False:
dir = "up"
r -= 1
elif r - 1 >= 0 and c + 1 < len(matrix[r]) and visited[r - 1][c + 1] is False:
dir = "up"
r -= 1
c += 1
elif c + 1 < len(matrix[r]) and visited[r][c + 1] is False:
dir = "up"
c += 1
elif r + 1 < len(matrix) and visited[r + 1][c] is False:
dir = "down"
r += 1
elif dir == "down":
if c == 0 or r == len(matrix) - 1:
if r + 1 < len(matrix) and visited[r + 1][c] is False:
dir = "up"
r += 1
elif c + 1 < len(matrix[r]) and visited[r][c + 1] is False:
dir = "up"
c += 1
else:
if r + 1 < len(matrix) and c - 1 >= 0 and visited[r + 1][c - 1] is False:
dir = "down"
r += 1
c -= 1
elif r + 1 < len(matrix) and visited[r + 1][c] is False:
dir = "down"
r += 1
return data``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.