Leetcode: Rotate Image

港控/mmm° 2022-08-07 13:36 241阅读 0赞

题目:
You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

思路分析:
最笨的方法,重新开辟一个矩阵空间,做旋转。(题目要求最好能就地旋转)
更好的方法:先将矩阵上下对折,然后再沿对角线对折。
例如:

  1. 1 2 3 7 8 9 7 4 1
  2. 4 5 6 -> 4 5 6 -> 8 5 2
  3. 7 8 9 1 2 3 9 6 3

OK,开始写代码!
C++参考代码:

  1. class Solution
  2. {
  3. public:
  4. void rotate(vector<vector<int> > &matrix)
  5. {
  6. if (matrix.empty()) return;
  7. int rows = int(matrix.size());
  8. int cell = 0;
  9. //上下对折
  10. for (int i = 0; i < rows / 2; ++i)
  11. {
  12. for (int j = 0; j < rows; ++j)
  13. {
  14. cell = matrix[i][j];
  15. matrix[i][j] = matrix[rows - i - 1][j];
  16. matrix[rows - i - 1][j] = cell;
  17. }
  18. }
  19. //对角线对折
  20. for (int i = 0; i < rows; ++i)
  21. {
  22. for (int j = 0; j < i; ++j)
  23. {
  24. cell = matrix[i][j];
  25. matrix[i][j] = matrix[j][i];
  26. matrix[j][i] = cell;
  27. }
  28. }
  29. }
  30. };

发表评论

表情:
评论列表 (有 0 条评论,241人围观)

还没有评论,来说两句吧...

相关阅读