Spiral Order Matrix II
Problem Description
Given an integer A, generate a square matrix filled with elements from 1 to A2 in spiral order and return the generated square matrix.
Problem Constraints
1 <= A <= 1000
Input Format
First and only argument is integer A
Output Format
Return a 2-D matrix which consists of the elements added in spiral order.
Example Input
Input 1:
1
Input 2:
2
Example Output
Output 1:
[ [1] ]
Output 2:
[ [1, 2],
[4, 3] ]
Example Explanation
Explanation 1:
Only 1 is to be arranged.
Explanation 2:
1 --> 2
|
|
4<--- 3
Output
Java
public class Solution {
public int[][] generateMatrix(int A) {
int[][] matrix = new int[A][A];
int top = 0, bottom = A - 1, left = 0, right = A - 1;
int num = 1;
while (top <= bottom && left <= right) {
// Fill top row
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
top++;
// Fill right column
for (int i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
right--;
// Fill bottom row
if (top <= bottom) {
for (int i = right; i >= left; i--) {
matrix[bottom][i] = num++;
}
bottom--;
}
// Fill left column
if (left <= right) {
for (int i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
left++;
}
}
return matrix;
}
}
Python
def generateMatrix(A):
matrix = [[0 for _ in range(A)] for _ in range(A)]
top, bottom, left, right = 0, A - 1, 0, A - 1
num = 1
while top <= bottom and left <= right:
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
return matrix
JavaScript
function generateMatrix(A) {
let matrix = new Array(A).fill(0).map(() => new Array(A).fill(0));
let top = 0,
bottom = A - 1,
left = 0,
right = A - 1;
let num = 1;
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) {
matrix[top][i] = num;
num++;
}
top++;
for (let i = top; i <= bottom; i++) {
matrix[i][right] = num;
num++;
}
right--;
if (top <= bottom) {
for (let i = right; i >= left; i--) {
matrix[bottom][i] = num;
num++;
}
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) {
matrix[i][left] = num;
num++;
}
left++;
}
}
return matrix;
}