蛇形填数 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);
    }
}
相关推荐
lsx2024065 分钟前
jQuery 删除元素
开发语言
遇见你...5 小时前
A01-Spring概述
java·后端·spring
代码匠心5 小时前
从零开始学Flink:TopN 榜单
大数据·后端·flink·flink sql·大数据处理
lizhongxuan7 小时前
Claude Code 防上下文爆炸:源码级深度解析
前端·后端
紫金修道7 小时前
【DeepAgent】概述
开发语言·数据库·python
Via_Neo7 小时前
JAVA中以2为底的对数表示方式
java·开发语言
书到用时方恨少!7 小时前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
cch89187 小时前
PHP五大后台框架横向对比
开发语言·php
天真萌泪8 小时前
JS逆向自用
开发语言·javascript·ecmascript
Warson_L8 小时前
Python 流程控制与逻辑
后端·python