如何修复遍历对角矩阵的代码(替代版本)?

时间:2019-04-16 12:22:44

标签: python python-3.x algorithm matrix

我有以下代码,用于交替打印对角矩阵。请查看我的代码,并告诉我它有什么问题?

class Solution:
    def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
        # No. of rows
        m=len(matrix)
        # No. of columns
        n=len(matrix[0])
        # Counter to alternatively switch the direction. 
        up=True
        # list to store the result
        l=[]
        i,j,count=0,0,0
        # loop for traversing all the elements.
        while(count<=m*n):
            if(up):
                while(i>=0 and j<n):
                    l.append(matrix[i][j])
                    count+=1
                    i-=1
                    j+=1
                if(i<0 and j<n):
                    i=0
                if(j==n):
                    i=i+2
                    j=j-1
            else:
                while(j>=0 and i<m):
                    l.append(matrix[i][j])
                    count+=1
                    j-=1
                    i+=1
                if(j<0 and i<m):
                    j=0
                if(i==m):
                    j=j+2
                    i=i-1
            up= not up
        print(l)

输入:

[
   [1,2,3],
   [4,5,6],
   [7,8,9]
]

预期答案:

  

[1,2,4,7,5,3,6,8,9]

实际答案:

  

第22行:IndexError:列表索引超出范围

1 个答案:

答案 0 :(得分:1)

您的代码有效,只需将您的while (count <= m * n)更改为while (count < m * n)

def findDiagonalOrder(matrix):
    # No. of rows
    m = len(matrix)
    # No. of columns
    n = len(matrix[0])
    # Counter to alternatively switch the direction. 
    up = True
    # list to store the result
    l = []
    i, j, count = 0, 0, 0
    # loop for traversing all the elements.
    while (count < m * n):
        if (up):
            while (i >= 0 and j < n):
                l.append(matrix[i][j])
                count += 1
                i -= 1
                j += 1
            if (i < 0 and j < n):
                i = 0
            if (j == n):
                i = i + 2
                j = j - 1
        else:
            while (j >= 0 and i < m):
                l.append(matrix[i][j])
                count += 1
                j -= 1
                i += 1
            if (j < 0 and i < m):
                j = 0
            if (i == m):
                j = j + 2
                i = i - 1
        up = not up
    print(l)

matrix = [
   [1,2,3],
   [4,5,6],
   [7,8,9]
]

findDiagonalOrder(matrix)
#[1, 2, 4, 7, 5, 3, 6, 8, 9]