Posts

Showing posts with the label Spiral Matrix II

Spiral Matrix II

Image
Given a positive integer   n , generate an   n x n   matrix   filled with elements from   1   to   n 2   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 Solution: 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 val = 1;         while (val <= n * n) {             for (int i = left; i <= right; i++)                  matrix[top][i] = val++;              top++;             for (int i = top; i <= bottom; i++)                 matrix[i][right] = val++;             right--;             for (int i = right; i >= left; i--)                 matrix[bottom][i] = val++;              botto