Spiral Matrix

1. Readme

螺旋矩阵

给定大小,以螺旋顺序返回数字的方阵.

矩阵应填充自然数字,从左上角的 1​​ 开始,以向内,顺时针螺旋顺序增加,如下例所示:

大小为 3 的螺旋矩阵
1 2 3
8 9 4
7 6 5
尺寸为 4 的螺旋矩阵
 1  2  3 4
12 13 14 5
11 16 15 6
10  9  8 7

资源

Reddit r/dailyprogrammer 挑战 #320 [简单]螺旋升天.https://www.reddit.com/r/dailyprogrammer/comments/6i60lr/20170619_challenge_320_easy_spiral_ascension/

2. 开始你的表演

pub fn spiral_matrix(size: u32) -> Vec<Vec<u32>> {
   unimplemented!(
       "Function that returns the spiral matrix of square size {}",
       size
   );
}

3. 测试代码查看


# #![allow(unused_variables)]
#fn main() {
#[test]
fn empty_spiral() {
   let expected: Vec<Vec<u32>> = Vec::new();
   assert_eq!(spiral_matrix(0), expected);
}

#[test]
//#[ignore]
fn size_one_spiral() {
   let mut expected: Vec<Vec<u32>> = Vec::new();
   expected.push(vec![1]);
   assert_eq!(spiral_matrix(1), expected);
}
#[test]
//#[ignore]
fn size_two_spiral() {
   let mut expected: Vec<Vec<u32>> = Vec::new();
   expected.push(vec![1, 2]);
   expected.push(vec![4, 3]);
   assert_eq!(spiral_matrix(2), expected);
}

#[test]
//#[ignore]
fn size_three_spiral() {
   let mut expected: Vec<Vec<u32>> = Vec::new();
   expected.push(vec![1, 2, 3]);
   expected.push(vec![8, 9, 4]);
   expected.push(vec![7, 6, 5]);
   assert_eq!(spiral_matrix(3), expected);
}
#[test]
//#[ignore]
fn size_four_spiral() {
   let mut expected: Vec<Vec<u32>> = Vec::new();
   expected.push(vec![1, 2, 3, 4]);
   expected.push(vec![12, 13, 14, 5]);
   expected.push(vec![11, 16, 15, 6]);
   expected.push(vec![10, 9, 8, 7]);
   assert_eq!(spiral_matrix(4), expected);
}
#[test]
//#[ignore]
fn size_five_spiral() {
   let mut expected: Vec<Vec<u32>> = Vec::new();
   expected.push(vec![1, 2, 3, 4, 5]);
   expected.push(vec![16, 17, 18, 19, 6]);
   expected.push(vec![15, 24, 25, 20, 7]);
   expected.push(vec![14, 23, 22, 21, 8]);
   expected.push(vec![13, 12, 11, 10, 9]);
   assert_eq!(spiral_matrix(5), expected);
}

#}

4. 答案


# #![allow(unused_variables)]
#fn main() {
pub fn spiral_matrix(size: u32) -> Vec<Vec<u32>> {
   let mut matrix: Vec<Vec<u32>> = vec![vec![0; size as usize]; size as usize];
   let num_concentric_squares = (size as f64 / 2.0).ceil() as usize;
   let mut counter: u32 = 1;
   let mut sidelen = size as usize;
   for i in 0..num_concentric_squares {
       for j in 0..sidelen {
           matrix[i][i + j] = counter;
           counter += 1;
       }

       for j in 1..sidelen {
           matrix[i + j][size as usize - 1 - i] = counter;
           counter += 1;
       }

       for j in (0..sidelen - 1).rev() {
           matrix[size as usize - 1 - i][i + j] = counter;
           counter += 1;
       }

       for j in (1..sidelen - 1).rev() {
           matrix[i + j][i] = counter;

           counter += 1;
       }
       if sidelen >= 2 {
           sidelen -= 2;
       } else {
           sidelen -= 1;
       }
   }
   matrix
}

#}



填充/相关