Python Hacky DFS... Any opinions?

  • 0

    So I basically do a DFS traversal prioritizing right, down, left, up directions, in that order, while mutating the array to mark positions that have been visited. The hacky part is when traversing up I force the DFS to prioritize traversing up as traversing right before up will be incorrect. Any opinions on my approach?

        def spiralOrder(self, matrix):
            def dfs(matrix, rList, r, c, upBit):
                if r < 0  or c < 0 or r >= len(matrix) or c >= len(matrix[0]) or matrix[r][c] == -sys.maxint:
                matrix[r][c] = -sys.maxint
                # right down left up
                if upBit: dfs(matrix, rList, r, c-1, True)
                dfs(matrix, rList, r-1, c, False)
                dfs(matrix, rList, r, c+1, False)
                dfs(matrix, rList, r+1, c, False)
                dfs(matrix, rList, r, c-1, True)
            if not matrix: return []
            rList = []
            dfs(matrix, rList, 0, 0, False)
            return rList

Log in to reply

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