蛇形填数 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);
    }
}
相关推荐
曾曜30 分钟前
PostgreSQL逻辑复制的原理和实践
后端
豌豆花下猫30 分钟前
Python 潮流周刊#110:JIT 编译器两年回顾,AI 智能体工具大爆发(摘要)
后端·python·ai
专注VB编程开发20年32 分钟前
各版本操作系统对.NET支持情况(250707更新)
开发语言·前端·ide·vscode·.net
我喜欢就喜欢40 分钟前
RapidFuzz-CPP:高效字符串相似度计算的C++利器
开发语言·c++
莫彩42 分钟前
【Modern C++ Part7】_创建对象时使用()和{}的区别
开发语言·c++
轻语呢喃44 分钟前
JavaScript :事件循环机制的深度解析
javascript·后端
ezl1fe1 小时前
RAG 每日一技(四):让AI读懂你的话,初探RAG的“灵魂”——Embedding
后端
经典19921 小时前
spring boot 详解以及原理
java·spring boot·后端
星光54221 小时前
飞算JavaAI:给Java开发装上“智能引擎”的超级助手
java·开发语言
Aurora_NeAr1 小时前
Apache Iceberg数据湖高级特性及性能调优
大数据·后端