蛇形填数 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);
    }
}
相关推荐
格林威几秒前
工业相机图像高速存储(C#版):内存映射文件方法,附海康相机C#实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·工业相机
csbysj2020几秒前
Lua 数据库访问
开发语言
弹简特3 分钟前
【JavaEE16-后端部分】SpringBoot日志的介绍
java·spring boot·后端
熊猫_豆豆4 分钟前
无人机表演点云路径规划(Python版)
开发语言·python·无人机·路径规划
廋到被风吹走4 分钟前
持续学习方向:云原生深度(Kubernetes Operator、Service Mesh、Dapr)
java·开发语言·学习
Source.Liu5 分钟前
【Iced】Iced:一种构建图形用户界面的新思维
rust·iced
程序喵大人5 分钟前
源码剖析:iostream 的缓冲区设计
开发语言·c++·iostream
泯仲6 分钟前
RabbitMQ的延迟消息在项目中的运用及实现剖析
开发语言·后端·rabbitmq
wapicn997 分钟前
技术实战:基于Python的企业信息四要素核验API调用示例
开发语言·python
xyq20247 分钟前
Scala 正则表达式
开发语言