Spiral Matrix II

theabbie

Abhishek Chaudhary

Posted on June 10, 2022

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
💖 💪 🙅 🚩
theabbie
Abhishek Chaudhary

Posted on June 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Balance a Binary Search Tree
leetcode Balance a Binary Search Tree

June 19, 2022

Implement Stack using Queues
leetcode Implement Stack using Queues

June 16, 2022

Sum of Digits in Base K
leetcode Sum of Digits in Base K

June 16, 2022

Permutation Sequence
leetcode Permutation Sequence

June 16, 2022