Leetcode problem solution-rotating image (detailed)

Code

var rotate = function(matrix) {
    
    
	let l = matrix.length;
	for(let i=0;i<parseInt((l+1)/2);i++){
    
    
		for(let j =0;j<parseInt(l/2);j++){
    
    
			let temp = matrix[l - 1 - j][i];
			matrix[l - 1 - j][i] = matrix[l - 1 - i][l - 1 - j];
			matrix[l - 1 - i][l - j - 1] = matrix[j][l - 1 -i];
			matrix[j][l - 1 - i] = matrix[i][j];
			matrix[i][j] = temp;
		}
	}
};

Ideas

Insert picture description here
Rotation is actually the rotation of four positions for each point.
So first calculate the coordinate relationship corresponding to these four points to achieve one exchange.
Assuming that the coordinates of the first point are (i,j) and the entire length is l,
we can understand that the four points are offset from the four vertices.
Then the ordinate of the second point should be equal to the abscissa of the first point because the offset is the same,
and the abscissa is the distance from the boundary so it is l-1-j,
so the coordinates of the second point ( l-1-j, i)
and so on to
get the coordinates of four points,
then only one auxiliary variable is needed to complete the exchange

How many points do you need to rotate to complete the overall rotation?
See the picture below

Insert picture description here
Because in fact, it only needs to rotate one point to cover the entire area.
There is a difference between odd and even numbers. The i direction is (n+1)/2. The j direction is n/2, whichever is smaller.

Guess you like

Origin blog.csdn.net/weixin_38616850/article/details/106415131