蛇形填数 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 分钟前
八股文整理——后端
java·开发语言·spring boot·后端·学习
自由的裙子3 分钟前
ASP.NET路由模型解析
后端·asp.net
matlab代码9 分钟前
基于matlab人脸门禁识别系统(可增加其它人脸图像)源码40期】
开发语言·matlab·人脸识别·人脸门禁
k↑22 分钟前
SpringCloud + React19 集成Scalar的API文档
后端·spring·spring cloud
Mandy的名字被占用了26 分钟前
Dart 与 Flutter 快速入门指南
后端·flutter·dart
货拉拉技术30 分钟前
基于eBPF的主机安全探索与实践
后端
梨子同志33 分钟前
Spring Security
后端
李少兄39 分钟前
Java CompletableFuture 解析(含常见面试题)
java·开发语言
名字还没想好☜39 分钟前
Spring Boot 全局异常处理:@ControllerAdvice 实战
java·spring boot·后端·spring·异常处理
还是鼠鼠1 小时前
AI掘金头条新闻系统 (Toutiao News)-缓存相关推荐新闻
后端·python·mysql·fastapi·web