How to generate an n x n matrix filled with elements from 1 to N^2 in spiral order in Rust

1 Answer

0 votes
fn generate_spiral_matrix(n: usize) -> Vec<Vec<i32>> {
    let mut matrix = vec![vec![0; n]; n];
    let (mut top, mut bottom) = (0, n as isize - 1);
    let (mut left, mut right) = (0, n as isize - 1);
    let mut num = 1;

    while top <= bottom && left <= right {
        // Fill top row
        for i in left..=right {
            matrix[top as usize][i as usize] = num;
            num += 1;
        }
        top += 1;

        // Fill right column
        for i in top..=bottom {
            matrix[i as usize][right as usize] = num;
            num += 1;
        }
        right -= 1;

        // Fill bottom row
        if top <= bottom {
            for i in (left..=right).rev() {
                matrix[bottom as usize][i as usize] = num;
                num += 1;
            }
            bottom -= 1;
        }

        // Fill left column
        if left <= right {
            for i in (top..=bottom).rev() {
                matrix[i as usize][left as usize] = num;
                num += 1;
            }
            left += 1;
        }
    }

    matrix
}

fn main() {
    let n = 3;
    let matrix = generate_spiral_matrix(n);

    for row in matrix {
        for val in row {
            print!("{}\t", val);
        }
        println!();
    }
}

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

*/

 



answered Jun 25 by avibootz
edited Jun 25 by avibootz
...