-
Notifications
You must be signed in to change notification settings - Fork 0
/
2326_spiral_matrix_iv.java
59 lines (51 loc) · 1.36 KB
/
2326_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
// 2326. Spiral Matrix IV
// Category: Array, Linked List, Matrix, Simulation
// Difficulty: Medium
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int[][] spiralMatrix(int m, int n, ListNode head) {
int[][] ans = new int[m][n];
for(int[] i : ans)
Arrays.fill(i,-1);
int l = 0 , r = n-1;
int top = 0 , bot = m-1;
ListNode th = head;
while(l <= r && top <= bot && th!=null)
{
for(int i = l ; i<=r && th!=null ;i++)
{
ans[top][i] = th.val;
th = th.next;
}
top++;
for(int i = top ; i<= bot && th!=null ;i++)
{
ans[i][r] = th.val;
th = th.next;
}
r--;
for(int i = r ; i>=l && th!=null ;i--)
{
ans[bot][i] = th.val;
th = th.next;
}
bot --;
for(int i = bot ; i>=top && th!=null ;i--)
{
ans[i][l] = th.val;
th = th.next;
}
l++;
}
return ans;
}
}