剣はオファー29を指します。マトリックスを時計回りに印刷します
タイトル説明
問題解決のアイデア
各レイヤーについて、すべての要素を左上から時計回りにトラバースします。現在のレイヤーの要素をトラバースした後、左と上を1増やし、右と下を1減らし、次のレイヤーに入り、トラバースするまでトラバースを続けます。すべての要素を終了します。
ピットがあることに注意してください!
ループ条件に起因するがwhile (left <= right && top <= bottom)
、現在の層が1列のみ(右==左)または唯一の行(上部==ボトム)を有する場合、唯一の上部と右の境界線は、そうでなければ繰り返し印刷が発生し、印刷する必要があります。
class Solution {
public int[] res;
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return new int[0];
//每一层的上下左右四个边界,从最外层开始
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
int[] res = new int[matrix.length * matrix[0].length];
int idx = 0; //res数组的指针
while (left <= right && top <= bottom) {
//上边界:(top, left) ~ (top, right)
for (int i = left; i <= right; i++) res[idx++] = matrix[top][i];
//右边界:(top + 1, right) ~ (bottom, right)
for (int i = top + 1; i <= bottom; i++) res[idx++] = matrix[i][right];
//注意!如果该层仅有一列或仅有一行,则只需打印上边界和右边界,否则会出现重复打印
if(left == right || top == bottom) break;
//下边界:(bottom, right - 1) ~ (bottom, left)
for (int i = right - 1; i >= left; i--) res[idx++] = matrix[bottom][i];
//左边界:(bottom - 1, left) ~ (top + 1, left)
for (int i = bottom - 1; i >= top + 1; i--) res[idx++] = matrix[i][left];
//进入下一层
left++; right--; top++; bottom--;
}
return res;
}
}