48. Rotate Image Medium
1/**
2 * [48] Rotate Image
3 *
4 * You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
5 * You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a>, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
6 *
7 * Example 1:
8 * <img alt="" src="https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg" style="width: 500px; height: 188px;" />
9 * Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
10 * Output: [[7,4,1],[8,5,2],[9,6,3]]
11 *
12 * Example 2:
13 * <img alt="" src="https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg" style="width: 500px; height: 201px;" />
14 * Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
15 * Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
16 *
17 *
18 * Constraints:
19 *
20 * n == matrix.length == matrix[i].length
21 * 1 <= n <= 20
22 * -1000 <= matrix[i][j] <= 1000
23 *
24 */
25pub struct Solution {}
26
27// problem: https://leetcode.com/problems/rotate-image/
28// discuss: https://leetcode.com/problems/rotate-image/discuss/?currentPage=1&orderBy=most_votes&query=
29
30// submission codes start here
31
32impl Solution {
33 pub fn rotate(matrix: &mut Vec<Vec<i32>>) {
34 let n = matrix.len();
35 for i in 0..n {
36 for j in i..n {
37 let tmp = matrix[i][j];
38 matrix[i][j] = matrix[j][i];
39 matrix[j][i] = tmp;
40 }
41 }
42
43 for i in 0..n {
44 for j in 0..n / 2 {
45 let tmp = matrix[i][j];
46 matrix[i][j] = matrix[i][n - 1 - j];
47 matrix[i][n - 1 - j] = tmp;
48 }
49 }
50 }
51}
52
53// submission codes end
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn test_48() {
61 let mut input = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
62 Solution::rotate(&mut input);
63 assert_eq!(
64 input,
65 vec![vec![7, 4, 1], vec![8, 5, 2], vec![9, 6, 3]]
66 );
67 }
68}
69
Back
© 2025 bowen.ge All Rights Reserved.