题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> res = new ArrayList<>(); if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ return res; } int rows = matrix.length-1; int column = matrix[0].length-1; int left = 0; int right = 0; int up = 0; int down = 0; for (int i = 0;;i++) { right = column-i; left = i; up = i; down = rows-i; if (left>right||up>down||right<0||down<0) { break; } //左往右 for (int j = left; j <= right; j++) { res.add(matrix[up][j]); } //上往下 for (int j = up+1; j <= down; j++) { res.add(matrix[j][right]); } //右往左, 必须加上 上小于下 for (int j = right-1; j>=left&&up<down; j--) { res.add(matrix[down][j]); } //下往上,必须加上左小于右 for (int j = down-1; j > up&&left<right; j--) { res.add(matrix[j][left]); } } return res; } }