矩阵按对角线打印---python

将一个矩阵(二维数组)按对角线向右进行打印。(搜了一下发现好像是美团某次面试要求半小时手撕的题)
Example:
Input:
[
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output:
[[4],
[3, 3],
[2, 2, 2],
[1, 1, 1],
[5, 5],
[9]]

class Solution():
    def print_matix(self,list):
        print(list)
        rows = len(list)
        cols = len(list[0])
        result = []
        for k in range(2*cols-1):    # 共输出 cols * 2 - 1 行
            diff = cols - k - 1  # 每一行的差
            for i in range(cols):    # 数组中每一个值的下标范围是0到cols
                for j in range(cols):
                    if j-i == diff:
                        print(list[i][j])
                        result.append(list[i][j])
            print()

        print(result)
        return result

    def diagonal_right(self,matrix):
        if not matrix:
            return []
        row = len(matrix)
        col = len(matrix[0])
        col2 = col
        result = []
        for i in range(row):
            for j in range(col2 - 1, -1, -1):  # j倒序遍历
                lst = []
                i1, j1 = i, j  # i1,j1用于方便同一对角线元素的添加,否则改变i,j影响开头元素的选择
                while i1 <= row - 1 and j1 <= col - 1:
                    lst.append(matrix[i1][j1])
                    j1 += 1
                    i1 += 1
                result.append(lst)
                if i == 0 and j == 0:  # 当遍历完(0,0)开头的一条对角线后,让j固定为0
                    col2 = 1
        return ('the result is: %s' % result, 'end')



if __name__ == '__main__':
     list = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
     solution = Solution()
     solution.print_matix(list)
     result = solution.diagonal_right(list)
     print(result)

 

posted @ 2020-03-11 09:39  图图图图胡图图  阅读(905)  评论(0编辑  收藏  举报