奇数建模 & 逆时针填格

把1-n*n个自然数填入n*n个格子中要求行,列,及对角线之和一致

import java.util.Scanner; public class AddModel { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; System.out.println("Input n(add):"); n = in.nextInt(); while ((n & 1) != 1) { System.out.println("Input n(add):"); n = in.nextInt(); } int[][] mat = new int[n][n]; int r0 = 0, r1, r2, c0 = n / 2, c1, c2, cnt = 1; mat[r0][c0] = cnt; while (true) { if(cnt == n * n) break; r1 = r0 - 1; c1 = c0 +1; if(r1 < 0) r1 = n -1; if(c1 > n-1) c1 = 0; if (mat[r1][c1] == 0) { mat[r1][c1] = ++cnt;r0 = r1; c0 = c1; } else { r2 = r0+1; c2 = c0; if(r2 > n-1) r2 = 0; mat[r2][c2] = ++cnt; r0 = r2; c0 = c2; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { System.out.print(mat[i][j] + "/t"); } System.out.println(); } } }


把n*n个数以逆时针的方式填入n*n个格子中

import java.util.*; public class AntiClockWise { public static void main (String[] args) { Scanner in = new Scanner(System.in); int[][] dir = new int[][]{{1,0},{0,1},{-1,0},{0,-1}}; System.out.println("Input n:"); int n = in.nextInt(); int[][] mat = new int[n][n]; int curr = 0, nextr = 0, curc = 0, nextc = 1, cnt = 1,type = 0; mat[0][0] = 1; while(true) { if(cnt == n*n) break; nextr = curr + dir[type][0]; nextc = curc + dir[type][1]; mat[nextr][nextc] = ++cnt; curr = nextr; curc = nextc; int next2r = curr + dir[type][0], next2c = curc + dir[type][1]; if( next2r < 0 || next2r >=n || next2c <0 || next2c >=n || mat[next2r][next2c] != 0) { type = (type+1) % 4; } } for(int i=0; i<n; ++i) { for(int j=0; j<n; ++j) { System.out.print(mat[i][j]+"/t"); } System.out.println(); } } }

P5447农场寻宝 入门 新手组 标准IO 传统题 时间限制 1000ms 内存限制 256MB 来源 TomAnderson 题目描述 面条在继承农场几个月后,突然收到了一份来自雪球的藏宝图。原来,雪球曾经在这个农场里埋下了一些宝藏,并希望通过这份藏宝图将这些宝藏送给面条。藏宝图上有很多指令,这些指令的内容是面条和雪球曾经约定好的,所以面条能够读懂。 每条指令是由五个数字组成的序列,可以翻译为转向的方向和要走的步数: 前两位数字表示转向的方向: 如果这两个数字的和是奇数,则转向左。 如果这两个数字的和是偶数且不为零,则转向右。 如果这两个数字的和为零,则保持与上一条指令相同的转向方向。 后三位数字表示要走的步数,步数至少为100。 现在,面条希望你能编写一个程序来翻译这些指令,帮助他找到宝藏。 输入式 若干行,每行一个五位的数字, 99999 99999 为结束的标志,并不需要翻译。 输出式 输出包含若干行,每行对应一个指令,由一个字符串和一个数字组成,用空隔开。 字符串为 left 或者 right,表示转向左或者转向右的方向。 数字表示要走的步数。 input1 复制代码 57234 00907 34100 99999 output1 复制代码 right 234 right 907 left 100 数据规模与约定 对于 100 % 100% 的数据,保证指令的个数不超过 200 200,保证第一个指令不以 00 00 开头
03-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值