54. Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

def spiralOrder(self, matrix: List[List[int]]):
    result = []
    rows, columns = len(matrix), len(matrix[0])
    up = left = 0
    right = columns - 1
    down = rows - 1

    while len(result) < rows * columns:       
        for col in range(left, right + 1): # Traverse from left to right.
            result.append(matrix[up][col])

        for row in range(up + 1, down + 1): # Traverse downwards.
            result.append(matrix[row][right])

    
        if up != down:   # Make sure we are now on a different row.
            for col in range(right - 1, left - 1, -1): # right to left.
                result.append(matrix[down][col])

        if left != right:  # Make sure we are now on a different column.
            for row in range(down - 1, up, -1): # Traverse upwards.
                result.append(matrix[row][left])

        left += 1
        right -= 1
        up += 1
        down -= 1

    return result




def spiralOrder(self, matrix: List[List[int]]):
    #dirs = ['R', 'D', 'L', 'U']
    curDir, r, c = 0, 0, 0
    R, C = len(matrix), len(matrix[0])
    width, height = C, R
    first = True  output = []
    w, h  = 1, 1
   
    while True:
        output.append(matrix[r][c])
       
        if curDir == 0 or curDir == 2:
            if w == width:
                curDir = (curDir+1)%4
                if not first:
                    width -= 1
                first = False
                w = 1
                if h == height:
                    break                                           
        else:
            if h == height:
                curDir = (curDir+1)%4
                height -= 1
                h = 1
                if w == width:
                    break
           
        if curDir == 0:
            c += 1                        
            w = 1 if w == width else w + 1
        elif curDir == 2:
            c -= 1
            w = 1 if w == width else w + 1
        elif curDir == 1:
            r += 1
            h = 1 if h == height else h+1
        else:
            r -= 1
            h = 1 if h == height else h+1
    return output

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break