逆时针输出矩阵

题目

逆时针输出矩阵

解答

public class NishizhenPrintJuzhen {

        public static int[][] getPrint(int n ){
            int[][] result = new int[n][n];
            int current = 0;
            //cycle为总循环次数
            for (int cycle = 0; cycle <= n / 2; cycle++) {

                //往右填充
                for (int right = cycle; right < n - cycle; right++) {

                    if (result[cycle][right] != 0) {
                        return result;
                    }
                    result[cycle][right] = current;
                    current++;

                }

                //往下填充
                for (int down = cycle + 1; down < n - cycle; down++) {
                    if (result[down][n - cycle - 1] != 0) {
                        return result;
                    }
                    result[down][n - cycle - 1] = current;
                    current++;
                }

                //往左填充
                for (int left = n - cycle - 2; left >= cycle; left--) {
                    if (result[n - cycle - 1][left] != 0) {
                        return result;
                    }
                    result[n - cycle - 1][left] = current;
                    current++;
                }

                //往上填充
                for (int up = n - cycle - 2; up >= cycle + 1; up--) {
                    if (result[up][cycle] != 0) {
                        return result;
                    }
                    result[up][cycle] = current;
                    current++;
                }
            }
            return result;
        }
        public static void main(String[] args) {

            int n = 5;
            int[][] result = getPrint(n);

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    System.out.print(result[i][j] + " ");
                }
                System.out.println();
            }
        }
}
点赞