package jianzhiOffer;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 输入一个矩阵,按照从外向里以顺时针的顺序依
 * 次打印出每一个数字,例如,如果输入如下矩阵: 
 * 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 
 * 则依次打印出数字1,2,3,4,8,12,16,15,14,13,
 * 9,5,6,7,11,10.
 * @author user
 * 思想,用左上和右下的坐标定位出一次要旋转打印
 * 的数据,一次旋转打印结束后,往对角分别前进和
 * 后退一个单位。提交代码时,主要的问题出在没有
 * 控制好后两个for循环,需要加入条件判断,防止
 * 出现单行或者单列的情况。
 */
public class ch19 {
	
	public static ArrayList<Integer> printMatrix(int [][] matrix) {
			ArrayList<Integer> arr = new ArrayList<>();
	       int rows = matrix.length;
	       int cols = matrix[0].length;
	       //如果输入了一个空的矩阵
	       if(rows == 0 || cols == 0) {
	    	   return null;
	       }
	       //坐标的定义
	       int top = 0,left = 0,bottom = rows - 1,right = cols - 1;
		   while(top <= bottom && left <= right) {
		       //从左往右
		       for (int i = left; i <= right; i++) arr.add(matrix[top][i]);
		       //从上往下
		       for (int j = top + 1; j <= bottom; j++) arr.add(matrix[j][right]);
		       //从右往左
		       if(top != bottom)
		    	   for (int k = right - 1; k >= left; k--) arr.add(matrix[bottom][k]);
		       //从下往上
		       if(left != right) 
		    	   for (int l = bottom - 1; l > top; l--) arr.add(matrix[l][left]);
		       top++;left++;bottom--;right--;
	       }
		   return arr;
    }
}