题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 import java.util.ArrayList; 2 3 /* 4 * 题目描述 5 * 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, 6 * 例如,如果输入如下4 X 4矩阵: 7 * 1 2 3 4 8 * 5 6 7 8 9 * 9 10 11 12 10 * 13 14 15 16 11 * 则依次打印出数字 12 * 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. 13 */ 14 15 public class Main19 { 16 17 public static void main(String[] args) { 18 // TODO Auto-generated method stub 19 int[][] matrix = { 20 {1,2,3,4}, 21 {5,6,7,8}, 22 {9,10,11,12}, 23 {13,14,15,16}, 24 {17,18,19,20} 25 }; 26 ArrayList<Integer> array = new ArrayList<>(); 27 array = Main19.printMatrix(matrix); 28 System.out.println(array); 29 } 30 31 public static ArrayList<Integer> printMatrix(int [][] matrix) { 32 ArrayList<Integer> array = new ArrayList<Integer>(); 33 if (matrix == null) { 34 return array; 35 } 36 37 int start = 0; 38 while (matrix[0].length > 2*start && matrix.length > 2*start) { 39 printOneCircle(matrix, start, array); 40 start++; 41 } 42 return array; 43 } 44 45 public static void printOneCircle(int[][] matrix, int start, ArrayList<Integer> array) { 46 int endX = matrix[0].length - 1 -start; 47 int endY = matrix.length - 1 - start; 48 49 for (int i=start;i<=endX;i++) { 50 array.add(matrix[start][i]); 51 } 52 53 if (start < endY) { 54 for (int i=start+1;i<=endY;i++) { 55 array.add(matrix[i][endX]); 56 } 57 } 58 59 if (start < endX && start <endY) { 60 for (int i=endX-1;i>=start;i--) { 61 array.add(matrix[endY][i]); 62 } 63 } 64 65 if (start < endX && start < endY - 1) { 66 for(int i=endY-1;i>start;i--) { 67 array.add(matrix[i][start]); 68 } 69 } 70 71 } 72 }