How to rotate square matrix 90 degrees to the left in Rust

1 Answer

0 votes
fn print_matrix(matrix: &Vec<Vec<i32>>) {
    for row in matrix {
        for val in row {
            print!("{} ", val);
        }
        println!();
    }
}

/**
 * Rotates a square matrix 90 degrees to the left (counterclockwise).
 * param matrix - The square matrix to rotate.
 */
fn rotate_matrix_90_degrees_left(matrix: &mut Vec<Vec<i32>>) {
    let len = matrix.len();

    // Validate input: Ensure it's a square matrix
    if !matrix.iter().all(|row| row.len() == len) {
        panic!("Input must be a square matrix.");
    }

    // Perform the rotation in-place
    for layer in 0..(len / 2) {
        let first = layer;
        let last = len - 1 - layer;

        for i in first..last {
            let offset = i - first;

            // Save the top element
            let top = matrix[first][i];

            // Move right to top
            matrix[first][i] = matrix[i][last];

            // Move bottom to right
            matrix[i][last] = matrix[last][last - offset];

            // Move left to bottom
            matrix[last][last - offset] = matrix[last - offset][first];

            // Move top to left
            matrix[last - offset][first] = top;
        }
    }
}

fn main() {
    let mut matrix = vec![
        vec![1, 2, 3],
        vec![4, 5, 6],
        vec![7, 8, 9],
    ];

    rotate_matrix_90_degrees_left(&mut matrix);

    println!("Matrix After 90° Left Rotation:");
    print_matrix(&matrix);
}



/*
run:

Matrix After 90° Left Rotation:
3 6 9 
2 5 8 
1 4 7 

*/

 



answered Oct 6, 2025 by avibootz

Related questions

...