【Java】P5731 【深基5.习6】蛇形方阵

【深基5.习6】蛇形方阵

题目描述

给出一个不大于 9 9 9 的正整数 n n n,输出 n × n n\times n n×n
的蛇形方阵。

从左上角填上 1 1 1 开始,顺时针方向依次填入数字,如同样例所示。注意每个数字有都会占用 3 3 3 个字符,前面使用空格补齐。

输入格式

输入一个正整数 n n n,含义如题所述。

输出格式

输出符合题目要求的蛇形矩阵。

样例 #1

样例输入 #1

4

样例输出 #1

1  2  3  4
 12 13 14  5
 11 16 15  6
 10  9  8  7

提示

数据保证, 1 ≤ n ≤ 9 1 \leq n \leq 9 1n9

代码

import java.io.*;
import java.util.*;

/**
 * @author: ZZJ
 * @date: 2023/01/30
 * @desc:
 */
public class Main {


    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        int nextInt = scanner.nextInt();
        int nums = nextInt * nextInt;
        int init = 1;
        int row = 0;
        int col = 0;
        int[][] ints = new int[nextInt][nextInt];
        while (init < nums){

            while (col + 1 < nextInt && ints[row][col+1] == 0) {
                ints[row][col++] = init++;
            }
            while (row + 1 < nextInt && ints[row+1][col] == 0){
                ints[row++][col] = init++;
            }
            while (col - 1 >= 0 && ints[row][col-1] == 0){
                ints[row][col--] = init++;
            }
            while (row - 1 >= 0 && ints[row-1][col] == 0){
                ints[row--][col] = init++;
            }
        }
        ints[row][col] = init;
        for (int i = 0; i < nextInt; i++) {
            for (int j = 0; j < nextInt; j++) {
                System.out.format("%3d",ints[i][j]);
            }
            System.out.println();
        }
    }
}

总结:row,col顺时针循环
请添加图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值