forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix IV.java
68 lines (48 loc) · 1.65 KB
/
Spiral Matrix IV.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
public int[][] spiralMatrix(int m, int n, ListNode head) {
int[][] ans=new int[m][n];
for(int[] arr:ans){
Arrays.fill(arr,-1);
}
int rowBegin=0;
int rowEnd=m-1;
int columnBegin=0;
int columnEnd=n-1;
ListNode cur=head;
while(rowBegin<=rowEnd && columnBegin<=columnEnd && cur!=null){
for(int i=columnBegin;i<=columnEnd && cur!=null;i++){
if(cur!=null){
ans[rowBegin][i]=cur.val;
}
cur=cur.next;
}
rowBegin++;
for(int i=rowBegin;i<=rowEnd && cur!=null;i++){
if(cur!=null){
ans[i][columnEnd]=cur.val;
}
cur=cur.next;
}
columnEnd--;
if(rowBegin<=rowEnd){
for(int i=columnEnd;i>=columnBegin && cur!=null;i--){
if(cur!=null){
ans[rowEnd][i]=cur.val;
}
cur=cur.next;
}
}
rowEnd--;
if(columnBegin<=columnEnd){
for(int i=rowEnd;i>=rowBegin && cur!=null;i--){
if(cur!=null){
ans[i][columnBegin]=cur.val;
}
cur=cur.next;
}
}
columnBegin++;
}
return ans;
}
}