--- python print matrix diagonally

A matrix (two-dimensional array) printed diagonally to the right. (Search, I found that the United States seems to be a group interview requires half an hour Shredded title)
Example:
the Input:
[
[1,2,3,4],
[5,1,2,3],
[9,5, 1,2]
]
the 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):     # total output cols * 2 - 1 rows 
            the diff = cols - K -. 1   # each line difference 
            for I in range (cols):     # array subscript range of each value is 0 to cols 
                for J in range (cols):
                     IF == JI 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 added for facilitating the same diagonal elements, or changing the i, j element affect the choice of the beginning 
                the 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:   # when traversed (0,0) at the beginning of a after the diagonal, so j is fixed at 0 
                    col2 =. 1 return ( ' the iS Result: 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)

 

Guess you like

Origin www.cnblogs.com/turningli/p/12460534.html