算法刷题(18)_逆时针打印矩阵学习记录


算法刷题(18)_逆时针打印矩阵学习记录

【说明】

题目:输入一个矩阵,按照从外向里以顺时针顺序依次打印出每一个数字,例如:如果输入如下矩阵: 
1   2   3   4 
5   6   7   8 
9  10 11 12 
13 14 15 16 

则依次打印出数字1, 5,9,13,14,15,16,12,8,4,3,2,6,10,11,7.

【算法实现】

package p4;

/**
 * 逆时针打印矩阵
 * @author Guozhu Zhu
 * @date 2018/7/29
 * @version 1.0
 *
 */
public class Test02 {
	
	public static void main(String[] args) {
		int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
		int[] res = Solution01(arr, 4, 3);
		for (int i : res) {
			System.out.println(i);
		}
	}
	
	public static int[] Solution01(int[][] arr, int n, int m) {
		int startX = 0;
		int startY = 0;
		int endX = m-1;
		int endY = n-1;
		int index = 0;
		int[] res = new int[n*m];
		while (startX <= endX && startY <= endY) {
			// 上---->下
			if (startY <= endY) {
				for (int i = startY; i <= endY; i++) {
					res[index++] = arr[i][startX];
				}
			}
			// 左---->右 (两列以上)
			if (startX < endX) {
				for (int i = startX+1; i <= endX; i++) {
					res[index++] = arr[endY][i];
				}
			}
			// 下---->上(两行两列以上)
			if (startX < endX && startY < endY) {
				for (int i = endY-1; i >= startY; i--) {
					res[index++] = arr[i][endX];
				}
			}
			// 右---->左(三列两行以上)
			if (startX < endX-1 && startY < endY) {
				for (int i = endX-1; i >= startX+1; i--) {
					res[index++] = arr[startY][i];
				}
			}
			startX++;
			startY++;
			endX--;
			endY--;
		}
		return res;
	}

}