-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spiral Matrix III.java
47 lines (42 loc) · 1.47 KB
/
Spiral Matrix III.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
// import java.util.*;
class Solution {
public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int numSteps = 1;
int totalCells = rows * cols;
List<int[]> result = new ArrayList<>();
int r = rStart, c = cStart;
int d = 0;
while (result.size() < totalCells) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < numSteps; j++) {
if (0 <= r && r < rows && 0 <= c && c < cols) {
result.add(new int[]{r, c});
}
if (result.size() == totalCells) {
return convertListToArray(result);
}
r += directions[d][0];
c += directions[d][1];
}
d = (d + 1) % 4;
}
numSteps++;
}
return convertListToArray(result);
}
private int[][] convertListToArray(List<int[]> list) {
int[][] array = new int[list.size()][2];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
return array;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] result = solution.spiralMatrixIII(5, 6, 1, 4);
for (int[] coords : result) {
System.out.println(Arrays.toString(coords));
}
}
}