import java.util.*;

public class Printer {
    public int[] clockwisePrint(int[][] mat, int n, int m) {
        // write code here
        //一共打印 count次就结束
        int count = n * m;
        int[] c = new int[count];

        boolean[][] visited = new boolean[n][m];

        //
        boolean shangHeng = true;
        boolean youShu = false;
        boolean xiaHeng = false;
        boolean zuoShu = false;
        int x = 0, y = 0, i = 0;
        while (i < count) {
            visited[x][y] = true;
            c[i] = mat[x][y];
            i++;

            //上横
            if (shangHeng) {
                //判断是否到边缘,到边缘就要调整方向
                if (y + 1 >= m || visited[x][y + 1]) {
                    shangHeng = false;
                    youShu = true;
                    x++;
                    continue;
                } else {
                    y++;
                }
            }
            //右竖
            if (youShu) {
                //判断是否到边缘,到边缘就要调整方向
                if (x + 1 >= n || visited[x + 1][y]) {
                    youShu = false;
                    xiaHeng = true;
                    y--;
                    continue;
                } else {
                    x++;
                }
            }

            //下横
            if (xiaHeng) {
                //判断是否到边缘,到边缘就要调整方向
                if (y - 1 < 0 || visited[x][y - 1]) {
                    xiaHeng = false;
                    zuoShu = true;
                    x--;
                    continue;
                } else {
                    y--;
                }
            }
            //左竖
            if (zuoShu) {
                //判断是否到边缘,到边缘就要调整方向
                if (x - 1 < 0 || visited[x - 1][y]) {
                    zuoShu = false;
                    shangHeng = true;
                    y++;
                    continue;
                } else {
                    x--;
                }
            }
        }
        return c;
    }
}