蛇形填数 rust解法

蛇形填数。

在n×n方阵里填入1,2,...,n×n,要求填成蛇形。例如,n=4时方阵为:

10 11 12 1

9 16 13 2

8 15 14 3

7 6 5 4

解法如下:

rust 复制代码
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);
    }
}
相关推荐
canonical_entropy19 小时前
AI时代,我们还需要低代码吗?—— 一场关于模型、演化与软件未来的深度问答
后端·低代码·aigc
颜如玉19 小时前
HikariCP:Dead code elimination优化
后端·性能优化·源码
考虑考虑20 小时前
Jpa使用union all
java·spring boot·后端
bobz96521 小时前
virtio vs vfio
后端
Rexi21 小时前
“Controller→Service→DAO”三层架构
后端
bobz9651 天前
计算虚拟化的设计
后端
深圳蔓延科技1 天前
Kafka的高性能之路
后端·kafka
Barcke1 天前
深入浅出 Spring WebFlux:从核心原理到深度实战
后端
JuiceFS1 天前
从 MLPerf Storage v2.0 看 AI 训练中的存储性能与扩展能力
运维·后端
大鸡腿同学1 天前
Think with a farmer's mindset
后端