輸出以下類任意階數的蛇形矩陣算法
1 2 1 2 3 01 02 03 04數組
4 3 8 9 4 12 13 14 05oop
7 6 5 11 16 15 06spa
10 09 08 07.net
根據蛇形賦值順序,能夠經過當前賦值的點座標(i,j)計算出下一個應該賦值的點。code
#[derive(Debug)] pub struct Matrix { matrix: Vec<Vec<usize>> } fn get_min(list:Vec<usize>) -> usize{ let mut min_num = list[0]; for num in list.iter(){ if num < &min_num{ min_num = *num; } } return min_num; } impl Matrix { pub fn new(size:usize) -> Matrix{ let mut matrix: Vec<Vec<usize>> = Vec::with_capacity(size); for _ in 0..size{ let mut temp: Vec<usize> = Vec::with_capacity(size); for _ in 0..size { temp.push(0); } matrix.push(temp); } let mut snake_matrix = Matrix{ matrix, }; (&mut snake_matrix).generate(size); return snake_matrix; } pub fn size(&self) -> usize{ self.matrix.len() } //計算出當前所在的圈數 fn get_loop(&self,point: &(usize,usize)) ->usize{ get_min(vec![point.0,point.1,self.size()-point.0-1,self.size()-point.1-1]) } pub fn get(&self,i:usize,j:usize) -> Result<usize,&str>{ let size = self.matrix.len(); if i >= size || j >= size{ Err("the index is out of range") }else{ Ok(self.matrix[i][j]) } } //當前節點賦值,並計算出下一個須要賦值的節點座標 fn next(&mut self,point:&mut (usize,usize),num:usize){ let &mut(i,j) = point; self.matrix[i][j] = num; let loop_count = self.get_loop(&point); if j>=i && i < self.size()-loop_count-1{ if j < self.size()-loop_count-1{ point.1 = j+1; }else{ point.0 = i+1; } }else { if j > loop_count{ point.1=j-1; }else if i > loop_count+1{ point.0=i-1; }else{ point.1=j+1; } } } fn generate(&mut self,size:usize) { let last_num = size * size; let mut point = (0,0); for num in 1..last_num+1 { self.next(&mut point,num); } } fn get_list(&self,index:usize)-> &Vec<usize>{ &self.matrix[index] } pub fn print_matrix(&self){ for i in 0..self.size() { println!("{:?}",self.get_list(i)); } } }
extern crate snakematrix; fn main() { let matrix = snakematrix::Matrix::new(5); matrix.print_matrix(); }
ps:若是想搞成外部輸入矩陣階數,能夠再參考個人另外一篇文章(rust控制檯整數讀取 )blog
~bla bla bla~ci
rust在比較和模式匹配時須要注意引用類型,不會自動解引用。之因此不在二維數組中存放vec的引用,而是直接存放vec,是因爲,Matrix類對二維數組具備徹底全部權。get