public ArrayList<Integer> printMatrix(int [][] matrix) { if (matrix == null || matrix.length == 0){ return new ArrayList<>(); } int up = 0; int right = matrix[0].length - 1; int down = matrix.length - 1; int left = 0; ArrayList<Integer> res = new ArrayList<>(); while (left <= right && up <= down){ for (int i = left; i <= right; i++) { res.add(matrix[up][i]); } for (int i = up + 1; i <= down; i++) { res.add(matrix[i][right]); } for (int i = right - 1; i >= left && left < right && down > up; i--) { res.add(matrix[down][i]); } for (int i = down - 1; i > up && down > up && left < right; i--) { res.add(matrix[i][left]); } up ++; right --; down --; left ++; } return res; }