# Spiral Matrix II Leetcode Solution

In this post, we are going 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.

## 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

Now, lets see the leetcode solution of Length of Last Word Leetcode Solution.

### Spiral Matrix II Leetcode Solution 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 Solutionin 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 Solution 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 Chase2learn This tutorial is only for Educational and Learning purposes.

NEXT: Permutation Sequence

Sharing Is Caring