LeetCode-48. Rotate Image

网友投稿 220 2022-08-29

LeetCode-48. Rotate Image

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

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image ​​in-place​​, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix = [ [1,2,3], [4,5,6], [7,8,9]],rotate the input matrix in-place such that it becomes:[ [7,4,1], [8,5,2], [9,6,3]]

Example 2:

Given input matrix =[ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16]], rotate the input matrix in-place such that it becomes:[ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11]]

题解:

先对角线交换,再左右交换即可

class Solution {public: void swap(int &a, int &b) { int idx = a; a = b; b = idx; } void rotate(vector>& matrix) { int n = matrix.size(); if (n <= 1) { return; } for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { swap(matrix[i][j], matrix[j][i]); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n / 2; j++) { swap(matrix[i][j], matrix[i][n - j - 1]); } } }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-102. Binary Tree Level Order Traversal
下一篇:巴萨时隔21年再度欧冠小组出局,主帅哈维“气坏了”!(哈维走后巴萨拿过欧冠吗)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~