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

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Linux Foundation Training and Certification

Teach Your Child To Read

Disclosure: My content contains affiliate links.

32,304 questions

42,479 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 

*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Sep 2 by avibootz
edited Sep 3 by avibootz

Related questions

1 answer 9 views
1 answer 10 views
1 answer 56 views
1 answer 53 views
1 answer 65 views
...