蛇形填数 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);
    }
}
相关推荐
ssshooter1 小时前
Tauri 项目实践:客户端与 Web 端的授权登录实现方案
前端·后端·rust
代码搬运媛1 小时前
Go 语言通道 (Channel) 深度用法讲解及实战
后端·go
程序员爱钓鱼2 小时前
Go生成唯一ID的标准方案:github.com/google/uuid使用详解
后端·google·go
Moment2 小时前
MinIO已死,MinIO万岁
前端·后端·github
无双_Joney2 小时前
心路散文 - 转职遇到AI浪潮,AIGC时刻人的价值是什么?
前端·后端·架构
树獭叔叔2 小时前
OpenClaw Tools 与 Skills 系统深度解析
后端·aigc·openai
树獭叔叔2 小时前
OpenClaw Memory 系统深度解析:从文件到向量的完整实现
后端·aigc·openai
程序猿阿越2 小时前
Kafka4源码(二)创建Topic
java·后端·源码阅读
悟空码字2 小时前
Spring Boot 整合 MongoDB 最佳实践:CRUD、分页、事务、索引全覆盖
java·spring boot·后端
开心就好20252 小时前
iOS App 安全加固流程记录,代码、资源与安装包保护
后端·ios