矩阵的对角遍历-建树层次遍历解法

一个二维矩阵要实现对角遍历:
矩阵的对角遍历-建树层次遍历解法_第1张图片
这个方法不一定是最快的,因为建树和复制的过程比较多。
其中关键的地方就是:如何建树 和 如何左右层次遍历

  1. 如何建树:1) 每个位置只能使用一次 2)建树其中一种方式:第一排均有左右孩子,其他仅有左孩子(也有其他方法,随你怎么建树)
  2. 如何左右层次遍历:一般的层次遍历仅为左分支先进或者右分支先进,可以再两层交换时,设定方向标识符,来交换方向
  3. 代码如下:
import itertools
from enum import Enum

class MatrixTreeNode:
    def __init__(self,left:tuple=None, right:tuple=None):
        self.left = left
        self.right = right

class DIRECTION(Enum):
    right = 1
    left = 0

class MatrixTree:
    def __init__(self):
        self.dict = {}
        # 方向标志
        self.direction = DIRECTION.left

    def buildTree(self, matrix):

        n = len(matrix)
        if n == 0:
            return
        m = len(matrix[0])
        if m == 0:
            return

        for i, j in itertools.product(range(0, n), range(0, m)):
            self.dict[(i, j)] = MatrixTreeNode()
            if i + 1 < n:
                self.dict[(i, j)].left = (i + 1, j)
            if i == 0 and j +1 < m:
                self.dict[(i, j)].right = (i, j + 1)

        return True

    def ReturnOrder(self):

        stack = [(0, 0)]
        preturn = []

        while len(stack) != 0:
            root = stack.pop()
            yield root
            if self.direction == DIRECTION.right:
                if self.dict[root].right is not None:
                    preturn.append(self.dict[root].right)
                if self.dict[root].left is not None:
                    preturn.append(self.dict[root].left)
            if self.direction == DIRECTION.left:
                if self.dict[root].left is not None:
                    preturn.append(self.dict[root].left)
                if self.dict[root].right is not None:
                    preturn.append(self.dict[root].right)
            if len(stack) == 0:
                stack, preturn = preturn, stack
                if self.direction == DIRECTION.left:
                    self.direction = DIRECTION.right
                else:
                    self.direction = DIRECTION.left






class Solution:

    def findDiagonalOrder(self, matrix: list) ->list:

        mt = MatrixTree()
        re = mt.buildTree(matrix)

        if re is None:
            return []

        result = []
        for coordinate in mt.ReturnOrder():
            result.append(matrix[coordinate[0]][coordinate[1]])
        return result

你可能感兴趣的:(Python,leetcode)