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.

39,926 questions

51,859 answers

573 users

How to print a given matrix in spiral form with Rust

1 Answer

0 votes
fn print_matrix_in_spiral_form(matrix: &[Vec<i32>]) {
    if matrix.is_empty() || matrix[0].is_empty() {
        return;
    }

    let (mut top, mut bottom) = (0, matrix.len() - 1);
    let (mut left, mut right) = (0, matrix[0].len() - 1);

    loop {
        if left > right {
            break;
        }

        // top row
        for i in left..=right {
            print!("{} ", matrix[top][i]);
        }
        println!();
        top += 1; // next row

        if top > bottom {
            break;
        }

        // right column
        for i in top..=bottom {
            print!("{} ", matrix[i][right]);
        }
        println!();
        right -= 1; // previous column

        if left > right {
            break;
        }

        // bottom row
        for i in (left..=right).rev() {
            print!("{} ", matrix[bottom][i]);
        }
        println!();
        bottom -= 1; // previous row

        if top > bottom {
            break;
        }

        // left column
        for i in (top..=bottom).rev() {
            print!("{} ", matrix[i][left]);
        }
        println!();
        left += 1; // next column
    }
}

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

    print_matrix_in_spiral_form(&matrix);
}


  
/*
run:

1 2 3 4 
8 12 16 
15 14 13 
9 5 
6 7 
11 
10 

*/

 



answered Sep 2, 2024 by avibootz
edited Sep 3, 2024 by avibootz

Related questions

1 answer 71 views
1 answer 75 views
1 answer 73 views
1 answer 88 views
1 answer 97 views
1 answer 114 views
1 answer 99 views
...