题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
一开始怎么也想不明白为啥要再每个for循环下面加if判断,不加的话这个例子[[1,2,3,4]]会输出1234321。
import java.util.*; import java.util.ArrayList; public class Solution { public static ArrayList<Integer> printMatrix(int[][] matrix) { ArrayList<Integer> res = new ArrayList(); if (matrix.length == 0) return null; int up = 0; int down = matrix.length - 1; int left = 0; int right = matrix[0].length - 1; while (left <= right && up <= down) { for (int i = left; i <= right; i++){ res.add(matrix[up][i]); } up++; if(up > down)break; for (int i = up; i <=down; i++){ res.add(matrix[i][right]); } right--; if(left > right)break; for (int i = right; i >=left;i--){ res.add(matrix[down][i]); } down--; if(up > down)break; for (int i = down; i >=up; i--){ res.add(matrix[i][left]); } left++; if(left > right)break; } return res; } }