一个用于遍历二维矩阵的常见方法,通常用于螺旋式遍历。这个模板是非常有用的,特别是在需要按特定顺序访问矩阵元素时,例如顺时针或逆时针遍历。这个方法可以确保您访问矩阵的每个元素,而不会遗漏或重复。
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
ans.add(array[top][column]) ;
}
for (int row = top + 1; row <= bottom; row++) {
ans.add(array[row][right]);
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
ans.add(array[bottom][column]);
}
for (int row = bottom; row > top; row--) {
ans.add(array[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
}