-
Notifications
You must be signed in to change notification settings - Fork 0
/
885. Spiral Matrix III
36 lines (28 loc) · 1.06 KB
/
885. Spiral Matrix III
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
class Solution {
public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int[][] directions = {
{0, 1}, // EAST
{1, 0}, // SOUTH
{0, -1}, // WEST
{-1, 0} // NORTH
};
int[][] result = new int[rows * cols][2];
int step = 0; // how many steps to move
int dir = 0; // which direction
result[0] = new int[]{rStart, cStart};
int count = 1;
while (count < rows * cols) {
// When we move EAST or WEST, we need to increase our steps by 1
if (dir == 0 || dir == 2) step++;
for (int i = 0; i < step; i++) {
rStart += directions[dir][0];
cStart += directions[dir][1];
if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) { // check valid
result[count++] = new int[]{rStart, cStart};
}
}
dir = (dir + 1) % 4; // turn to next direction
}
return result;
}
}