Implementing a function that returns a n x m matrix in counter-clockwise spiral order starting from at the bottom right entry of the matrix

Implementing a function that returns a n x m matrix in counter-clockwise spiral order starting from at the bottom right entry of the matrix

Problem Description:

So I’m trying to implement a function in python that returns all elements of a n x m matrix in counter-clockwise spiral order, starting at the bottom furthest-right entry of the matrix.

For example, let’s say the input was:

matrix = [[1,2,3],
          [4,5,6],
          [7,8,9]] 

Then our output would be [9, 6, 3, 2, 1, 4, 7, 8, 5]

In another case, if the

matrix = [[1,2],
          [3,4],
          [5,6]]

Then our output would be [6, 4, 2, 1, 3, 5]

And finally, if the matrix = [3], we’d return [3].

The function I’m implementing follows this header:

def spiralOrder(matrix: list[list[int]]) -> list[int]:

Solution – 1

You could consider using a while-loop:

def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
    result = []
    left, right = 0, len(matrix[0]) - 1
    up, down = 0, len(matrix) - 1
    step = 0
    while left <= right and up <= down:
        match step % 4:
            case 0:
                for i in range(down, up - 1, -1):
                    result.append(matrix[i][right])
                right -= 1
            case 1:
                for i in range(right, left - 1, -1):
                    result.append(matrix[up][i])
                up += 1
            case 2:
                for i in range(up, down + 1):
                    result.append(matrix[i][left])
                left += 1
            case 3:
                for i in range(left, right + 1):
                    result.append(matrix[down][i])
                down -= 1
        step += 1
    return result

Example Usage 1:

print(spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[9, 6, 3, 2, 1, 4, 7, 8, 5]

Example Usage 2:

print(spiralOrder([[1, 2], [3, 4], [5, 6]])
[6, 4, 2, 1, 3, 5]

Example Usage 3:

print(spiralOrder([[3]])
[3]

Note: [3] is a not of the type list[list[int]] hence I am assuming it is a typo in your question.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject