1 package com.exe4.offer; 2 3 import java.util.ArrayList; 4 /** 5 * 17【题目】输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 6 * 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. 7 * @author WGS 8 * 9 */ 10 public class PrintArraysInCircle { 11 12 public ArrayList<Integer> printArraysClock(int[][] arrs){ 13 int rows=arrs.length; 14 int columns=arrs[0].length; 15 if(arrs==null || rows<=0 || columns<=0) 16 return null; 17 18 ArrayList<Integer> list=new ArrayList<Integer>(); 19 //起点坐标 20 int count=0; 21 while(columns>count*2 && rows>count*2){ 22 printArraysInCircle(list,arrs,columns,rows,count); 23 count++; 24 } 25 return list; 26 } 27 28 29 30 public void printArraysInCircle(ArrayList<Integer> list,int[][] arrs,int columns,int rows,int count) { 31 int endX=columns-1-count; 32 int endY=rows-1-count; 33 int number=0; 34 35 //从左到右打印》》》》》》 36 for(int i=count;i<=endX;i++){ 37 list.add(arrs[count][i]); 38 } 39 //从上到下打印 40 if(count<endX){ 41 for(int i=count+1;i<=endY;i++){ 42 list.add(arrs[i][endX]); 43 } 44 } 45 //从右到左 46 if(count<endX && count<endY){ 47 for(int i=endX-1;i>=count;i--){ 48 list.add(arrs[endY][i]); 49 } 50 } 51 //从下到上 52 if(count<endX && count<endY-1){ 53 for(int i=endY-1;i>=count+1;i--){ 54 list.add(arrs[i][count]); 55 } 56 } 57 58 } 59 60 61 62 public static void main(String[] args) { 63 // TODO Auto-generated method stub 64 int[][] arrs = new int[4][4]; 65 arrs[0] = new int[]{1,2,3,4}; 66 arrs[1] = new int[]{5,6,7,8}; 67 arrs[2] = new int[]{9,10,11,12}; 68 arrs[3] = new int[]{13,14,15,16}; 69 // matrix[4] = new int[]{17,18,19,20}; 70 71 PrintArraysInCircle p = new PrintArraysInCircle(); 72 ArrayList<Integer> list = p.printArraysClock(arrs); 73 for (Integer integer : list) { 74 System.out.print(integer+" "); 75 } 76 } 77 78 }