题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> list = new ArrayList<>(); //特殊情况 if(matrix.length==0){ return list; } int up = 0; int down = matrix.length-1; int left = 0; int right = matrix[0].length-1; while(up<=down&&left<=right){ //向右 for(int i=left;i<=right;i++){ list.add(matrix[up][i]); } up++; if(up>down){ break; } //向下 for(int i=up;i<=down;i++){ list.add(matrix[i][right]); } right--; if(left>right){ break; } //向左 for(int i=right;i>=left;i--){ list.add(matrix[down][i]); } down--; if(down<up){ break; } //向上 for(int i=down;i>=up;i--){ list.add(matrix[i][left]); } left++; if(left>right){ break; } } return list; } }