# Spiral Matrix II LeetCode Solution

Here, We see Spiral Matrix II LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

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]]
```

## Spiral Matrix II Leetcode Solution C++

``````class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int> (n, 1));
int left, right, top, down, index;
left = top = index = 0, right = down = n-1;
while (left <= right && top <= down) {
for (unsigned int j = left; j <= right; j++)
res[top][j] = ++index;
top++;
for (unsigned int i = top; i <= down; i++)
res[i][right] = ++index;
right--;
for (int j = right; j >= left; j--)
res[down][j] = ++index;
down--;
for (int i = down; i >= top; i--)
res[i][left] = ++index;
left++;
}
return res;
}
};```Code language: PHP (php)```

## Spiral Matrix II Leetcode Solution Java

``````class Solution {
public int[][] generateMatrix(int n) {
int[][] ret = new int[n][n];
int left = 0,top = 0;
int right = n -1,down = n - 1;
int count = 1;
while (left <= right) {
for (int j = left; j <= right; j ++) {
ret[top][j] = count++;
}
top ++;
for (int i = top; i <= down; i ++) {
ret[i][right] = count ++;
}
right --;
for (int j = right; j >= left; j --) {
ret[down][j] = count ++;
}
down --;
for (int i = down; i >= top; i --) {
ret[i][left] = count ++;
}
left ++;
}
return ret;
}
}```Code language: PHP (php)```

## Spiral Matrix II Leetcode Solution JavaScript

``````var generateMatrix = function(n) {
const M = [...Array(n)].map(() => Array(n).fill(0));
let x = 0, y = 0, dx = 1, dy = 0;
for (let i = 1, nn = n**2; i <= nn; ++i) {
M[y][x] = i;
if (!M[y + dy] || M[y + dy][x + dx] !== 0)
[dx, dy] = [-dy, dx];
x += dx;
y += dy;
}
return M;
};```Code language: JavaScript (javascript)```

## Spiral Matrix II Leetcode Solution Python

``````class Solution(object):
def generateMatrix(self, n):
A = [[0] * n for _ in range(n)]
i, j, di, dj = 0, 0, 0, 1
for k in xrange(n*n):
A[i][j] = k + 1
if A[(i+di)%n][(j+dj)%n]:
di, dj = dj, -di
i += di
j += dj
return A``````
Scroll to Top