🌕 885. 螺旋矩阵 III
2022年6月9日
- algorithm
🌕 885. 螺旋矩阵 III
难度: 🌕
问题描述
解法
class Solution {
int rows;
int cols;
public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
// 思路:
// 从 [rStart, cStart] 点开始
// 👉 1 👇1 👈 2 👆 2 👉3 👇 3 👈 4 👆 4
// 找规律
this.rows = rows;
this.cols = cols;
int len = rows * cols;
int[][] res = new int[len][2];
int index = 0;
int i = rStart;
int j = cStart;
int step = 1;
while(index < len) {
// 向右走 step 步
for(int m = 0; m < step; m ++) {
if(isValid(i, j)) {
res[index][0] = i;
res[index][1] = j;
// System.out.println(index + " aaaa " + Arrays.toString(res[index]));
index ++;
if(index == len)
return res;
}
j ++;
}
// 向下走 step 步
for(int m = 0; m < step; m ++) {
if(isValid(i, j)) {
res[index][0] = i;
res[index][1] = j;
// System.out.println(index + " bbbbb " + Arrays.toString(res[index]));
index ++;
if(index == len)
return res;
}
i ++;
}
// 向左走 step + 1 步
step ++;
for(int m = 0; m < step; m ++) {
if(isValid(i, j)) {
res[index][0] = i;
res[index][1] = j;
// System.out.println(index + " cccc " + Arrays.toString(res[index]));
index ++;
if(index == len)
return res;
}
j --;
}
// 向上走 step + 1 步
for(int m = 0; m < step; m ++) {
if(isValid(i, j)) {
res[index][0] = i;
res[index][1] = j;
// System.out.println(index + " dddd " + Arrays.toString(res[index]));
index ++;
if(index == len)
return res;
}
i --;
}
step ++;
}
return res;
}
private boolean isValid(int i, int j) {
if(i < 0 || j < 0) {
return false;
}
if(i >= rows || j >= cols) {
return false;
}
return true;
}
}