简体   繁体   中英

Time Complexity of Spirally Traversing a 2D Matrix?

I am learning how to traverse a 2D matrix spirally, and I came across this following algorithm:

def spiralOrder(self, matrix):

    result = []

    while matrix:
        result.extend(matrix.pop(0))
        matrix = zip(*matrix)[::-1]

    return result

I am currently having a hard time figuring out the time complexity of this question with the zip function being in the while loop.

It would be greatly appreciated if anyone could help me figure out the time complexity with explanations.

Thank you!

The known time complexity for this problem is a constant O(MxN) where M is the number of rows and N is the number of columns in a MxN matrix. This is an awesome algorithm but it looks like it might be slower.

Looking at it more closely, with every iteration of the loop you are undergoing the following operations:

pop() # O(1)
extend() # O(k) where k is the number of elements added that operation
*matrix # O(1) -> python optimizes unpacking for native lists
list(zip()) # O(j) -> python 2.7 constructs the list automatically and python 3 requires the list construction to run
[::-1] # O(j/2) -> reverse sort divided by two because zip halved the items

Regardless of how many loop iterations, by the time this completes you will have at least called result.extend on every element (MxN elements) in the matrix. So best case is O(MxN).

Where I am less sure is how much time the repeated zips and list reversals are adding. The loop is only getting called roughly M+N-1 times but the zip/reverse is done on (M-1) * N elements and then on (M-1) * (N-1) elements, and so on. My best guess is that this type of function is at least logarithmic so I would guess overall time complexity is somewhere around O(MxN log(MxN)).

https://wiki.python.org/moin/TimeComplexity

No matter how you traverse a 2D matrix, the time complexity will always be quadratic in terms of the dimensions.

A m×n matrix therefore takes O(mn) time to traverse, regardless if it is spiral or row-major.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM