劍指offer(十九)——順時針打印矩陣

劍指offer(十九)——順時針打印矩陣

題目描述
輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下4 X 4矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

題解
這種題就是我們學基本語法二維數組時遇到的類似蛇形矩陣的東西,說到底就是如何遍歷數組的問題,難點在於邊界的判定和移動方向的改變。

  • 我們可以知道,當matrix[i][j]到達左上角,右上角,左下角,右下角的時候就要改變方向,因此我們用四個變量來記錄這些邊界。
public static ArrayList<Integer> printMatrix(int [][] matrix) {
		//遍歷結果存儲在這個數組中
		ArrayList<Integer> resultList = new ArrayList<>();
		//邊界
		int leftEdge = 0, rightEdge = matrix[0].length - 1, upEdge = 0, downEdge = matrix.length - 1;
		//matrix的大小
		int count = matrix[0].length * matrix.length;
		//方向
		int[][] dir = new int[][] {{0,1},{1,0},{0,-1},{-1,0}};
		int i = 0, j = 0, dirCount = 0, direction = 0;
		while(count != 0) {
			//當向右走並且到達邊界時,改變方向和邊界
			if (direction == 0 && j == rightEdge) {
				dirCount ++;
				upEdge ++;
			}
			//當向下走並且到達邊界時,改變方向和邊界
			if (direction == 1 && i == downEdge) {
				dirCount ++;
				rightEdge --;
			}
			//當向左走並且到達邊界時,改變方向和邊界
			if (direction == 2 && j == leftEdge) {
				dirCount ++;
				downEdge --;
			}
			//當上右走並且到達邊界時,改變方向和邊界
			if (direction == 3 && i == upEdge) {
				dirCount ++;
				leftEdge ++;
			}
			direction = dirCount % 4;
			//測試:i和j值。調試時用的
//			System.out.println(i + " " + j);
			resultList.add(matrix[i][j]);
			//移動
			i += dir[direction][0];
			j += dir[direction][1];
			count--;
		}
		return resultList;     
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章