-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSpiralMatrix4.java
72 lines (63 loc) · 1.73 KB
/
SpiralMatrix4.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
/*https://leetcode.com/problems/spiral-matrix-iv/*/
class Solution {
public int[][] spiralMatrix(int m, int n, ListNode head) {
int[][] matrix = new int[m][n];
int i, j, rs = 0, re = m-1, cs = 0, ce = n-1;
for (i = 0; i < m; ++i)
Arrays.fill(matrix[i],-1);
i = j = 0;
ListNode temp = head;
while (temp != null)
{
//add the top row
for (j = cs; j <= ce; ++j)
{
if (temp != null)
{
matrix[i][j] = temp.val;
temp = temp.next;
}
else break;
}
//delete top row
++rs; --j;
//add right column
for (i = rs; i <= re; ++i)
{
if (temp != null)
{
matrix[i][j] = temp.val;
temp = temp.next;
}
else break;
}
//delete right column
--ce; --i;
//add bottom row
for (j = ce; j >= cs; --j)
{
if (temp != null)
{
matrix[i][j] = temp.val;
temp = temp.next;
}
else break;
}
//delete bottom row
--re; ++j;
//add left column
for (i = re; i >= rs; --i)
{
if (temp != null)
{
matrix[i][j] = temp.val;
temp = temp.next;
}
else break;
}
//delete left column
++cs; ++i;
}
return matrix;
}
}