MrainW's Home

All things come to those who wait!

0%

LeetCode 59. Spiral Matrix II

Question

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

https://leetcode.com/problems/spiral-matrix-ii/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
if (n <= 0) return res;
int top = 0, bottom = n - 1;
int left = 0, right = n - 1;
int k = 1;
while (top < bottom && left < right) {
for (int i = left; i < right; i++) res[top][i] = k++;
for (int i = top; i < bottom; i++) res[i][right] = k++;
for (int i = right; i > left; i--) res[bottom][i] = k++;
for (int i = bottom; i > top; i--) res[i][left] = k++;
top++;
bottom--;
left++;
right--;
}
if (n %2 != 0) res[n / 2][n / 2] = k;
return res;
}
}

Complexity:

Time complexity: O(mn)

Space complexity: O(mn)

Welcome to my other publishing channels