顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字 。样例输入:[[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 = idx[d], y = jdy[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;}}