Title Description
There is an image represented by the NxN matrix, where each pixel is represented by an int, write an algorithm that rotates the image 90 degrees clockwise without occupying additional memory space (that is, without using the cache matrix).
Given a nxn matrix, and the order of the Matrix N, return the rotated NxN matrix, guaranteeing that n is less than or equal to 500, the image element is less than or equal to 256.
Test examples:
[[1,2,3],[4,5,6],[7,8,9]],3
return: [[7,4,1],[8,5,2],[9,6,3]]
Solution: My idea is to first swap the rows, then swap the two columns, and finally get the rotated matrix.
1.vector as a new use of two-dimensional arrays
2. Swapping with the swamp function can also
#include <iostream> #include <string> #include <vector>using namespace std;void printmat (vector< Vector<int> > Mat, int n) {for (int i=0; i < n; i++) {for (int j = 0; J < N; j + +) cout < < Mat[i][j] << ""; cout << Endl; }}vector<vector<int> > Transformimage (vector<vector<int> > Mat, int n) {//90 degree flip, first diagonal interchange, then 0 with N-1 between the column interchange can//first diagonal interchange for (int i = 0; i < n; i++) {for (int j = i + 1; j < N; j + +) {//Here I and J are equal without the need to swap int temp; temp = Mat[i][j]; Mat[i][j] = mat[j][i];mat[j][i] = temp;}} Column vector Interchange for (int j = 0; J < N/2; J + +) for (int i = 0; i < n; i++) {int temp = mat[i][j];mat[i][j] = mat[i][n-j-1];mat[ I][N-J-1] = temp;} Printmat (Mat, N); return mat;} int main (int argc, char** argv) {int n = 5;vector<vector<int> > Array (n);//3 vectors for (int i = 0; i < n; i++) {array[i].resize (n);//sets the size of the array 3x3} for (int i = 0; i < n; i++) {for (int J = 0; J < N; J + +) {Array[i][j] = (n * i + 1 + j); }}//Output cout << "original image:" << endl;printmat (array, n); cout << "90 degree rotated array:" << endl;transformimage (array, n); return 0; }
1.6 Array-pixel flip