A/C Python solution, easy to understand, beat 73%


  • 0
    W

    class Solution(object):
    def findDiagonalOrder(self, matrix):
    """
    :type matrix: List[List[int]]
    :rtype: List[int]
    """
    numRow = len(matrix)
    # print "numRow = ", numRow
    if numRow < 1:
    return []
    numCol = len(matrix[0])
    # print "numCol = ", numCol
    rowIdx, colIdx = 0, 0
    res = []
    curDir = 0

        for i in range(numCol * numRow):
            # print "i = ", i, " curDir = ", curDir
            # print "rowIdx = ", rowIdx, " colIdx = ", colIdx, " matrix[rowIdx][colIdx] = ", matrix[rowIdx][colIdx]
            res.append(matrix[rowIdx][colIdx])
            # print "res = ", res
            if (curDir == 0):
                newRowIdx = rowIdx - 1
                newColIdx = colIdx + 1
            elif (curDir == 1):
                newRowIdx = rowIdx + 1
                newColIdx = colIdx - 1
    
            # print "need test newRowIdx ", newRowIdx, " newColIdx = ", newColIdx
            if newRowIdx >= 0 and newRowIdx < numRow and newColIdx >= 0 and newColIdx < numCol:
                rowIdx = newRowIdx
                colIdx = newColIdx
    
                continue
            elif newColIdx == numCol:
                # print "got top right corner"
                rowIdx = rowIdx + 1
                colIdx = numCol - 1
    
                curDir = (curDir + 1) % 2
            elif newRowIdx == numRow:
                colIdx += 1
    
                curDir = (curDir + 1) % 2
            else:
                # print "need change direction, newRowIdx = ", newRowIdx, " newColIdx = ", newColIdx
                if (curDir == 0):
                    colIdx = newColIdx
                elif (curDir == 1):
                    rowIdx = newRowIdx
                curDir = (curDir + 1) % 2
        return res

Log in to reply
 

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