题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
样例
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
算法1
$O(n^2)$
时间复杂度
JAVA 代码
class Solution {
public int[] printMatrix(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int m = matrix.length;
int n = matrix[0].length;
int[] res = new int[m * n];
int[] dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
int x = 0, y = 0, d = 0;
int[][] mark = new int[m][n];
for (int i = 0; i < m*n; i++) {
res[i] = matrix[x][y];
mark[x][y] = 1;
int a = x + dx[d];
int b = y + dy[d];
if (a < 0 || a >= m || b < 0 || (b) >= n || mark[a][b] == 1){
d = (d + 1) % 4;
a = x + dx[d];
b = y + dy[d];
}
x = a;
y = b;
}
return res;
}
}