题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param matrix int整型二维数组 # @return int整型一维数组 # class Solution: def printMatrix(self, matrix): # write code here n = len(matrix) m = len(matrix[0]) if not m or not n: # 特殊条件1,空 return [] if n == 1: # 特殊条件2,一行 return matrix[0] if m == 1: # 特殊条件3,一列 return [item[0] for item in matrix] flag = [[False] * m for _ in range(n)] # 其他情况 direct = 0 # 表示当前正在游走的方向 wherego = 0 # 表示接下来拐弯应去向何方 i, j = 0, 0 res = [] while flag[i][j] == False: if wherego == 0: # 其实默认为0,向右 while j < m - 1 and flag[i][j] == False: res.append(matrix[i][j]) flag[i][j] = True # 走过的路定位False j += 1 # 向右 direct = 1 # 当前游走位置为1 wherego = 1 # 接下来将去往1,这两个1含义不同,自己是自己的 if wherego == 1: while i < n - 1 and flag[i][j] == False: res.append(matrix[i][j]) flag[i][j] = True i += 1 direct = 2 wherego = 2 if wherego == 2: while j >= 1 and flag[i][j] == False: res.append(matrix[i][j]) flag[i][j] = True j -= 1 direct = 3 wherego = 3 if wherego == 3: while i >= 1 and flag[i][j] == False: res.append(matrix[i][j]) flag[i][j] = True i -= 1 direct = 4 if direct == 1: # 如果循环是从direct=1的方向跳出来的,那么接下来去向wherego=1的循环,以下同理 j -= 1 # 对应循环跳出,i,j重新调整 i += 1 wherego = 1 elif direct == 2: j -= 1 i -= 1 wherego = 2 elif direct == 3: j += 1 i -= 1 wherego = 3 else: i += 1 j += 1 wherego = 0 return res