洛谷P5731 【深基5.习6】蛇形方阵java版题解

编程入门 行业动态 更新时间:2024-10-25 13:14:27

洛谷P5731 【深基5.习6】<a href=https://www.elefans.com/category/jswz/34/1672817.html style=蛇形方阵java版题解"/>

洛谷P5731 【深基5.习6】蛇形方阵java版题解

 

import java.util.Arrays;
import java.util.Scanner;// 给出一个不大于9的正整数n,输出n×n的蛇形方阵。
public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int[][] a = new int[n][n];int total = 1;int x = 0;int y = 0;a[x][y] = 1;while (total <n * n) {while (y<n-1 && a[x][y+1] == 0) {a[x][++y] = ++total;}while (x<n-1 && a[x+1][y] == 0) {a[++x][y] = ++total;}while (y>0 && a[x][y-1] == 0) {a[x][--y] = ++total;}while (x>0 && a[x-1][y] == 0) {a[--x][y] = ++total;}}for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {System.out.printf("%3d",a[i][j]);}System.out.println();}}
}

更多推荐

洛谷P5731 【深基5.习6】蛇形方阵java版题解

本文发布于:2023-11-15 17:13:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603288.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:蛇形   题解   方阵   洛谷   深基

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!