public static int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int[][] result = new int[rows * cols][2];
int resultIndex = 0;
// Directions: right, down, left, up
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int currRow = rStart, currCol = cStart;
int step = 1; // Step size
int dir = 0; // Direction index
result[resultIndex++] = new int[]{currRow, currCol};
while (resultIndex < rows * cols) {
for (int i = 0; i < 2; i++) { // Each step size repeats twice, spiral law
for (int j = 0; j < step; j++) {
currRow += directions[dir][0];
currCol += directions[dir][1];
// Only add valid cells to result
if (currRow >= 0 && currRow < rows && currCol >= 0 && currCol < cols) {
result[resultIndex++] = new int[]{currRow, currCol};
}
}
dir = (dir + 1) % 4; // Rotate direction
}
step++; // Increase step size every two turns
}
return result;
}
Why Increase step Every Two Moves?
Right (1 step) → Down (1 step) → Left (2 steps) → Up (2 steps) → Right (3 steps) → Down (3 steps) → ...