forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix II.java
43 lines (35 loc) · 1.07 KB
/
Spiral Matrix II.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 69.11%)
class Solution {
public int[][] generateMatrix(int n) {
int startingRow = 0;
int endingRow = n-1;
int startingCol = 0;
int endingCol = n-1;
int total = n*n;
int element = 1;
int[][] matrix = new int[n][n];
while(element<=total){
for(int i = startingCol; element<=total && i<=endingCol; i++){
matrix[startingRow][i] = element;
element++;
}
startingRow++;
for(int i = startingRow; element<=total && i<=endingRow; i++){
matrix[i][endingCol] = element;
element++;
}
endingCol--;
for(int i = endingCol; element<=total && i>=startingCol; i--){
matrix[endingRow][i] = element;
element++;
}
endingRow--;
for(int i = endingRow; element<=total && i>=startingRow; i--){
matrix[i][startingCol] = element;
element++;
}
startingCol++;
}
return matrix;
}
}