顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
样例
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
模拟
时间复杂度O(n^2)
使用top、bottom、left、right表示边界
超出右边界(y > right)时,上边界加1(++top)
超出下边界(x > bottom)时,右边界减1(–right)
超出左边界(y < left)时,下边界减1(–bottom)
超出上边界(x < top)时,左边界加1(++left)
class Solution {
public int[] printMatrix(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
final int m = matrix.length;
final int n = matrix[0].length;
int[] res = new int[m * n];
// 方向: 右, 下, 左, 上
final int[] dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
int d = 0;
int top = 0, bottom = m - 1, left = 0, right = n - 1;
// 初始位置
int i = 0, j = -1;
for (int k = 0; k < m * n; ) {
final int x = i + dx[d], y = j + dy[d];
if (x >= top && x <= bottom && y >= left && y <= right) {
res[k] = matrix[x][y];
i = x;
j = y;
++k;
} else {
// 调整边界
if (y > right) {
++top;
} else if (x > bottom) {
--right;
} else if (y < left) {
--bottom;
} else /*if(x < top)*/ {
++left;
}
// 调整方向
++d;
d &= 3;
}
}
return res;
}
}