In this post, you will know how to solve the Spiral Matrix II Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Leetcode by yourself. If you find any difficulty after trying several times, then you can look for solutions.
Problem
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
Spiral Matrix II Leetcode Solutions in Python
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: ans = [[0] * n for _ in range(n)] count = 1 for min in range(n // 2): max = n - min - 1 for i in range(min, max): ans[min][i] = count count += 1 for i in range(min, max): ans[i][max] = count count += 1 for i in range(max, min, -1): ans[max][i] = count count += 1 for i in range(max, min, -1): ans[i][min] = count count += 1 if n & 1: ans[n // 2][n // 2] = count return ans
Spiral Matrix II Leetcode Solutions in CPP
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> ans(n, vector<int>(n)); int count = 1; for (int min = 0; min < n / 2; ++min) { const int max = n - min - 1; for (int i = min; i < max; ++i) ans[min][i] = count++; for (int i = min; i < max; ++i) ans[i][max] = count++; for (int i = max; i > min; --i) ans[max][i] = count++; for (int i = max; i > min; --i) ans[i][min] = count++; } if (n & 1) ans[n / 2][n / 2] = count; return ans; } };
Spiral Matrix II Leetcode Solutions in Java
class Solution { public int[][] generateMatrix(int n) { int[][] ans = new int[n][n]; int count = 1; for (int min = 0; min < n / 2; ++min) { final int max = n - min - 1; for (int i = min; i < max; ++i) ans[min][i] = count++; for (int i = min; i < max; ++i) ans[i][max] = count++; for (int i = max; i > min; --i) ans[max][i] = count++; for (int i = max; i > min; --i) ans[i][min] = count++; } if (n % 2 == 1) ans[n / 2][n / 2] = count; return ans; } }
Note: This problem Spiral Matrix II is generated by Leetcode but the solution is provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.
Next: Permutation Sequence Leetcode Solution