Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,036 questions

52,001 answers

573 users

How to rotate a matrix 90 degrees clockwise in Rust

2 Answers

0 votes
fn rotate90_clockwise(matrix: &mut Vec<Vec<i32>>) {
    let n = matrix.len();

    // Step 1: Transpose the matrix
    for i in 0..n {
        for j in i..n {
            let temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }

    // Step 2: Reverse each row
    for row in matrix.iter_mut() {
        row.reverse();
    }
}

fn print_matrix(matrix: &Vec<Vec<i32>>) {
    for row in matrix {
        println!("{}", row.iter().map(|x| x.to_string()).collect::<Vec<String>>().join(" "));
    }
}

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

    println!("Original Matrix:");
    print_matrix(&matrix);

    rotate90_clockwise(&mut matrix);

    println!("\nRotated Matrix:");
    print_matrix(&matrix);
}

   
    
/*
run:
    
Original Matrix:
1 2 3
4 5 6
7 8 9

Rotated Matrix:
7 4 1
8 5 2
9 6 3
    
*/

 



answered May 30, 2025 by avibootz
0 votes
fn rotate90_clockwise(matrix: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    let rows = matrix.len();
    let cols = matrix[0].len();
    
    // Create a new rotated matrix
    let mut rotated = vec![vec![0; rows]; cols];

    // Map values to rotated positions
    for i in 0..rows {
        for j in 0..cols {
            rotated[j][rows - 1 - i] = matrix[i][j];
        }
    }

    rotated
}

fn print_matrix(matrix: &Vec<Vec<i32>>) {
    for row in matrix {
        println!("{}", row.iter().map(|x| x.to_string()).collect::<Vec<String>>().join(" "));
    }
}

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

    println!("Original Matrix:");
    print_matrix(&matrix);

    let rotated = rotate90_clockwise(matrix);

    println!("\nRotated Matrix:");
    print_matrix(&rotated);
}

   
    
/*
run:
    
Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12

Rotated Matrix:
9 5 1
10 6 2
11 7 3
12 8 4
    
*/

 



answered May 30, 2025 by avibootz

Related questions

2 answers 140 views
2 answers 151 views
2 answers 175 views
2 answers 129 views
...