def spiral_order(matrix):
    if not matrix or not matrix[0]:
        return []
    top, bottom = 0, len(matrix)
    left, right = 0, len(matrix[0])
    output = []
    while top < bottom and left < right:
        for c in range(left, right):
            output.append(matrix[top][c])
        top += 1
        for r in range(top, bottom):
            output.append(matrix[r][right - 1])
        right -= 1
        if top < bottom:
            bottom -= 1
            for c in range(right - 1, left - 1, -1):
                output.append(matrix[bottom][c])
        if left < right:
            for r in range(bottom - 1, top - 1, -1):
                output.append(matrix[r][left])
            left += 1
    return output
