leetcodeLC102: rotate-image (Java implementation)

Title description

Give an image represented by a two-dimensional matrix

Returns the result of rotating the image 90 degrees clockwise

Expansion:

Can you use the in-place algorithm to solve this problem?

 

Ideas:

1. Get the number of rows and columns of the matrix. For example, a matrix with m rows and n columns will become n rows and m columns after being rotated 90 degrees clockwise.

2. Create a new array other to store the rotated data. Scan the original matrix by row and column, and grasp the corresponding relationship between the original matrix and the flipped matrix: other[j][row-i-1]=matrix[i][j]

3. Finally, assign the elements in other to the matrix one by one.

 

Note: The in-situ algorithm requires changing the original matrix. I originally wanted to change the reference method, but it failed the test. In this way, matrix=other directly makes the matrix abandon the original reference point, thereby pointing to the other array object. This method does not work, you must modify the matrix in turn.

public class Solution {
    public  void rotate(int[][] matrix) {
        int i, j;
        int rows, colomns;

        //java中获取二维数组行和列的方式
        colomns = matrix[0].length;
        rows = matrix.length;

        int[][] other = new int[colomns][rows];

        for (i = 0; i < rows; i++)
            for (j = 0; j < colomns; j++) {
                other[j][rows - i - 1] = matrix[i][j];
            }

        //修改原matrix
        for (i = 0; i < rows; i++) {
            for (j = 0; j < colomns; j++) {
                matrix[i][j]=other[i][j];
            }
        }
       //使用matrix=other这种方法取代上面的修改是不行的
    }
}

 

Guess you like

Origin blog.csdn.net/Zhongtongyi/article/details/107222889