矩陣轉置

概述:

    實現 n×m 的矩陣的順時針、逆時針旋轉,以及n×n的矩陣沿 y=x 和 y=-x 的對摺。

實現思路:

    對於矩陣轉置這一類問題,關鍵在於找出轉置前後的位置關係。
    以2×3的矩陣的順時針旋轉爲例:
        原矩陣:

            1,2,3
            4,5,6

        轉置後:

            4,1
            5,2
            6,3

        找出轉置前後的位置關係:

            (0,0) -> (0,1) -> (0,2-1-0)
            (0,1) -> (1,1) -> (1,2-1-0)
            (0,2) -> (2,1) -> (2,2-1-0)
            (1,0) -> (0,0) -> (0,2-1-1)
            (1,1) -> (1,0) -> (1,2-1-1)
            (1,2) -> (2,0) -> (2,2-1-1)

        所以轉置前後的關係爲(設矩陣爲 n×m 的矩陣):

            (x,y) -> (y,n-1-x)

    其它情況的矩陣轉置和上面一樣。

    代碼實現如下:

public class ArrayRotation {

	/**
	 * 順時針旋轉
	 * @param array
	 * @return
	 */
	public int[][] clockwiseRotation(int[][] array) {
		int rows = array.length;
		int cols = 0;
		for (int i = 0; i < array.length; i++) {
			int tmp = array[i].length;
			if (tmp > cols) {
				cols = tmp;
			}
		}
		int[][] traned = new int[cols][rows];
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array[i].length; j++) {
				traned[j][rows - 1 - i] = array[i][j];
			}
		}
		return traned;
	}

	/**
	 * 逆時針旋轉
	 * @param array
	 * @return
	 */
	public int[][] anticlockwiseRotation(int[][] array) {
		int rows = array.length;
		int cols = 0;
		for (int i = 0; i < array.length; i++) {
			int tmp = array[i].length;
			if (tmp > cols) {
				cols = tmp;
			}
		}
		int[][] traned = new int[cols][rows];
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array[i].length; j++) {
				traned[cols - 1 - j][i] = array[i][j];
			}
		}
		return traned;
	}

	/**************************/
	/**
	 * 沿 y = -x 對摺
	 * @param array
	 * @return
	 */
	public int[][] fold(int[][] array) {
		int rows = array.length;
		int cols = 0;
		for (int i = 0; i < array.length; i++) {
			int tmp = array[i].length;
			if (tmp > cols) {
				cols = tmp;
			}
		}
		if (cols == rows) {
			int[][] traned = new int[cols][rows];
			for (int i = 0; i < array.length; i++) {
				for (int j = 0; j < array[i].length; j++) {
					traned[j][i] = array[i][j];
				}
			}
			return traned;
		}
		return null;
	}

	/**
	 * 沿 y = x 對摺
	 * @param array
	 * @return
	 */
	public int[][] antiFold(int[][] array) {
		int rows = array.length;
		int cols = 0;
		for (int i = 0; i < array.length; i++) {
			int tmp = array[i].length;
			if (tmp > cols) {
				cols = tmp;
			}
		}
		if (cols == rows) {
			int[][] traned = new int[cols][rows];
			for (int i = 0; i < array.length; i++) {
				for (int j = 0; j < array[i].length; j++) {
					traned[cols - 1 - j][rows - 1 - i] = array[i][j];
				}
			}
			return traned;
		}
		return null;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章