Sprial Matrix || problem leetcode
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
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int num = 1; // Start filling from 1 to n^2
while (num <= n * n) {
// Move right
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
top++;
// Move down
for (int i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
right--;
// Move left
if (top <= bottom) {
for (int i = right; i >= left; i--) {
matrix[bottom][i] = num++;
}
bottom--;
}
// Move up
if (left <= right) {
for (int i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
left++;
}
}
return matrix;
}
public static void main(String[] args) {
Solution sol = new Solution();
int n = 3; // Example input
int[][] result = sol.generateMatrix(n);
// Print the matrix
for (int[] row : result) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
Comments
Post a Comment