Swap the top left with the top right, then swap the top left with the right bottom, and finally swap the top left with the left bottom. Continue this process until all elements in the matrix are swapped.
fn swap(matrix: &mut Vec<Vec<i32>>, pos_1: (usize, usize), pos_2: (usize, usize)) {
let temp = matrix[pos_1.0][pos_1.1];
matrix[pos_1.0][pos_1.1] = matrix[pos_2.0][pos_2.1];
matrix[pos_2.0][pos_2.1] = temp;
}
impl Solution {
pub fn rotate(matrix: &mut Vec<Vec<i32>>) {
let n = matrix.len();
for i in 0..n/2 {
let length = n - 2 * i;
let last = i + length - 1;
for j in 0..length-1 {
if i == 1 {
println!("i: {}, j: {}, length: {}", i, j, length);
}
let left_corner = (i, i+j);
swap(matrix, left_corner, (i+j, last));
swap(matrix, left_corner, (last, last-j));
swap(matrix, left_corner, (last-j, i));
}
}
}
}
Practice Dates
Description
Link: https://leetcode.com/problems/rotate-image/description/
Solution
Swap the top left with the top right, then swap the top left with the right bottom, and finally swap the top left with the left bottom. Continue this process until all elements in the matrix are swapped.
Performance
Time complexity: