标签:
题目:You are given an n x n 2D matrix represengting an image.
Rotate the image by 90 degrees(clockwise).
Follow up:
Could you do this in-place?
给定一副由 N * N 矩阵表示的图像,其中每个像素的大小为4字节,
编写一个方法,将图像旋转 90 度(顺时针)。不占额外内存空间能否做到?
来源:https://leetcode.com/problems/rotate-image/
解答:
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 class Solution { 6 public: 7 void rotate(vector< vector<int> > &matrix) 8 { 9 if (matrix.size() == 0) { 10 return; 11 } 12 int row = matrix.size(); 13 int col = matrix[0].size(); 14 15 if (row != col) { 16 return; 17 } 18 // 先按行换 19 for (int i = 0; i < row / 2; ++i) { 20 for (int j = 0; j < col; ++j) 21 swap(matrix[i][j], matrix[row - i - 1][j]); 22 } 23 // 再按主对角线换 24 for (int i = 0; i < row; ++i) { 25 for (int j = 0; j < col; ++j) { 26 if (i > j) { 27 swap(matrix[i][j], matrix[j][i]); 28 } 29 } 30 } 31 } 32 33 private: 34 void swap(int &lhs, int &rhs) 35 { 36 int temp = lhs; 37 lhs = rhs; 38 rhs = temp; 39 } 40 }; 41 42 int main(void) 43 { 44 Solution sl; 45 46 int n = 1; 47 cout << "Enter the matrix‘s dem:"; 48 cin >> n; 49 50 vector< vector<int> >matrix(n, vector<int>(n)); 51 for (int i = 0; i < n; ++i) { 52 for (int j = 0; j < n; ++j) { 53 matrix[i][j] = i * n + j + 1; 54 } 55 } 56 57 cout << "Before:" << endl; 58 for (int i = 0; i < n; ++i) { 59 for (int j = 0; j < n; ++j) { 60 cout << matrix[i][j] << " "; 61 } 62 cout << endl; 63 } 64 sl.rotate(matrix); 65 66 cout << "After:" << endl; 67 for (int i = 0; i < n; ++i) { 68 for (int j = 0; j < n; ++j) { 69 cout << matrix[i][j] << " "; 70 } 71 cout << endl; 72 } 73 74 return 0; 75 }
标签:
原文地址:http://www.cnblogs.com/cloudfeng/p/4451762.html