蛇形填数 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);
    }
}
相关推荐
qyzm24 分钟前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
月月玩代码26 分钟前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
leluckys37 分钟前
swift- Swift中常见的面试题
开发语言·汇编·swift
BUG_MeDe42 分钟前
json格式字符串解析的简单使用 libjson-c
c语言·开发语言·json
XPoet1 小时前
AI 编程工程化:Skill——给你的 AI 员工装上技能包
前端·后端·ai编程
CoderCodingNo1 小时前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法
码事漫谈2 小时前
从“功能实现”到“深度优化”:金仓数据库连接条件下推技术的演进之路
后端
码事漫谈2 小时前
数据库查询优化中的谓词下推策略与成本感知优化实践
后端