Rotating square matrix p363

Given a square matrix, please adjust the matrix to be rotated 90° clockwise. The additional space complexity required is O(1).
Insert picture description here
Idea: Take the above figure as an example, first select the points 1, 3 on the four corners of the matrix ,9,7, according to the clockwise direction 1 to 3 positions (1->3), 3->9, 9->7, 7->1, so for the rotated matrix, these four points It has been adjusted. Then only need to adjust the positions of 2, 6, 8, 4, the adjustment method is the same.
Just use the same method to adjust the first n-1 points of the first row of the matrix , and adjust the first n-3 points of the second row of the matrix..., then it is easy to adjust the n-order matrix.
Insert picture description here
Above, the four black dots are a group, a total of three (n-1) groups

package class_03;

public class Code_05_RotateMatrix {
    
    

	public static void rotate(int[][] matrix) {
    
    
		int tR = 0;
		int tC = 0;
		int dR = matrix.length - 1;
		int dC = matrix[0].length - 1;????????????
		while (tR < dR) {
    
    
			rotateEdge(matrix, tR++, tC++, dR--, dC--);
		}
	}

	public static void rotateEdge(int[][] m, int tR, int tC, int dR, int dC) {
    
    
		int times = dC - tC; //times表示组数
		int tmp = 0;
		for (int i = 0; i != times; i++) {
    
    //一次循环就是一组占据调整
			tmp = m[tR][tC + i];
			m[tR][tC + i] = m[dR - i][tC];
			m[dR - i][tC] = m[dR][dC - i];
			m[dR][dC - i] = m[tR + i][dC];
			m[tR + i][dC] = tmp;
		}
	}

	public static void printMatrix(int[][] matrix) {
    
    
		for (int i = 0; i != matrix.length; i++) {
    
    
			for (int j = 0; j != matrix[0].length; j++) {
    
    
				System.out.print(matrix[i][j] + " ");
			}
			System.out.println();
		}
	}

	public static void main(String[] args) {
    
    
		int[][] matrix = {
    
     {
    
     1, 2, 3, 4 }, {
    
     5, 6, 7, 8 }, {
    
     9, 10, 11, 12 },
				{
    
     13, 14, 15, 16 } };
		printMatrix(matrix);
		rotate(matrix);
		System.out.println("=========");
		printMatrix(matrix);

	}

}

Guess you like

Origin blog.csdn.net/Mr_zhang66/article/details/113660468