蛇形填数。
在n×n方阵里填入1,2,…,n×n,要求填成蛇形。例如,n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
解法如下:
use std::io;fn main() {let mut buf = String::new();io::stdin().read_line(&mut buf).unwrap();let n: usize = buf.trim().parse().unwrap();let mut arr = vec![vec![0; n]; n];let mut i = 1;let mut x = 0;let mut y = n - 1;arr[x][y] = 1;while i < n * n {while x + 1 < n && arr[x + 1][y] == 0 {i += 1;x += 1;arr[x][y] = i;}while y > 0 && arr[x][y - 1] == 0 {i += 1;y -= 1;arr[x][y] = i;}while x > 0 && arr[x - 1][y] == 0 {i += 1;x -= 1;arr[x][y] = i;}while y + 1 < n && arr[x][y + 1] == 0 {i += 1;y += 1;arr[x][y] = i;}}for row in &arr {println!("{:?}", row);}
}