顺时针打印矩阵
方向数组太好用啦
class Solution {
public int[] printMatrix(int[][] matrix) {
int row = matrix.length;
if (row == 0)
return new int[]{};
int col = matrix[0].length;
int n = row * col;
int[] res = new int[n];
int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
int d = 1, x = 0, y = 0;
for (int i = 0; i < n; i++) {
res[i] = matrix[x][y];
matrix[x][y] = -1;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= row || b < 0 || b >= col || matrix[a][b] == -1) {
d = (d + 1) % 4;
a = x + dx[d];
b = y + dy[d];
}
x = a;
y = b;
}
return res;
}
}