蛇形填数 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);
    }
}
相关推荐
鹏易灵2 分钟前
C++——2.常量与 const、constexpr 初识详解
java·开发语言·c++
苍何2 分钟前
高考填志愿,我做了个 Skill,300 个 Agent 同时查公司
后端
yspwf11 分钟前
NestJS 配置管理完整方案
后端·架构·node.js
神仙别闹17 分钟前
基于C++ 实现 BP 神经网络
开发语言·c++·神经网络
雪隐21 分钟前
个人电脑玩AI-03让5060 Ti给你打工——paddleOCR
人工智能·后端
AskHarries28 分钟前
Shell Tool:命令执行、输出读取和长任务管理
后端
苍何31 分钟前
开源项目想出海,我让 AI 员工帮我找海外达人
后端
疯狂成瘾者33 分钟前
Java 集合 LinkedList 详解:链表结构、常用方法和队列使用
java·开发语言·链表
望眼欲穿的程序猿33 分钟前
读取芯片内部温度传感器
嵌入式硬件·rust
望眼欲穿的程序猿35 分钟前
ADC 模拟电压采集
嵌入式硬件·rust