DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

2 1

Spiral Matrix II

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

Input: n = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 20

SOLUTION:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        matrix = [[-1 for i in range(n)] for j in range(n)]
        ctr = 0
        direction = 0
        x, y = 0, 0
        while ctr < n * n:
            if matrix[x][y] == -1:
                ctr += 1
                matrix[x][y] = ctr
            switch = False
            if direction == 0:
                if (y + 1) < n and matrix[x][y + 1] == -1:
                    y += 1
                else:
                    switch = True
            elif direction == 1:
                if (x + 1) < n and matrix[x + 1][y] == -1:
                    x += 1
                else:
                    switch = True
            elif direction == 2:
                if (y - 1) >= 0 and matrix[x][y - 1] == -1:
                    y -= 1
                else:
                    switch = True
            else:
                if (x - 1) >= 0 and matrix[x - 1][y] == -1:
                    x -= 1
                else:
                    switch = True
            if switch:
                direction = (direction + 1) % 4
        return matrix
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay