码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-03-11 11:10:20      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:put   and   result   固定   维数   print   范围   on()   遍历   

将一个矩阵(二维数组)按对角线向右进行打印。(搜了一下发现好像是美团某次面试要求半小时手撕的题)
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)

 

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

标签:put   and   result   固定   维数   print   范围   on()   遍历   

原文地址:https://www.cnblogs.com/turningli/p/12460534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!