import java.util.ArrayList;
public class Solution {
    
    ArrayList<Integer> res = new ArrayList<>();
    
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        
        int x1 = 0;
        int y1 = 0;
        int x2 = matrix.length - 1;
        int y2 = matrix[0].length - 1;
        while (x1 <= x2 && y1 <= y2) {
            process(matrix, x1++, y1++, x2--, y2--);
        }
        return res;
    }
    
    public void process(int[][] matrix, int x1, int y1, int x2, int y2) {
        if (x1 == x2) {
            for (int i = y1; i <= y2; i++) {
                res.add(matrix[x1][i]);
            }
        }
        else if (y1 == y2) {
            for (int i = x1; i <= x2; i++) {
                res.add(matrix[i][y1]);
            }
        }
        else {
            int currentx = x1;
            int currenty = y1;
            while (currenty != y2) {
                res.add(matrix[x1][currenty]);
                currenty++;
            }
            while (currentx != x2) {
                res.add(matrix[currentx][y2]);
                currentx++;
            }
            while (currenty != y1) {
                res.add(matrix[x2][currenty]);
                currenty--;
            }
            while (currentx != x1) {
                res.add(matrix[currentx][y1]);
                currentx--;
            }
        }
    }
}