forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_2326.java
77 lines (71 loc) · 2.17 KB
/
_2326.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
69
70
71
72
73
74
75
76
77
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import java.util.ArrayList;
import java.util.List;
public class _2326 {
public static class Solution1 {
public int[][] spiralMatrix(int m, int n, ListNode head) {
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
int[][] matrix = new int[m][n];
int i = 0;
int j = 0;
int index = 0;
int rightBorder = n - 1;
int bottom = m - 1;
int leftBorder = 0;
int top = 1;
int count = 0;
while (index < m * n) {
//go right
while (j <= rightBorder) {
matrix[i][j++] = index < list.size() ? list.get(index++) : -1;
count++;
}
if (count >= m * n) {
return matrix;
}
rightBorder--;
j--;
//go down
i++;
while (i <= bottom) {
matrix[i++][j] = index < list.size() ? list.get(index++) : -1;
count++;
}
if (count >= m * n) {
return matrix;
}
i--;
bottom--;
//go left
j--;
while (j >= leftBorder) {
matrix[i][j--] = index < list.size() ? list.get(index++) : -1;
count++;
}
if (count >= m * n) {
return matrix;
}
j++;
leftBorder++;
//go top
i--;
while (i >= top) {
matrix[i--][j] = index < list.size() ? list.get(index++) : -1;
count++;
}
if (count >= m * n) {
return matrix;
}
i++;
top++;
j++;
}
return matrix;
}
}
}