螺旋数字矩阵

package testing; /** * 43 44 45 46 47 48 49 50 * 42 21 22 23 24 25 26 . * 41 20 7 8 9 10 27 . * 40 19 6 1 2 11 28 . * 39 18 5 4 3 12 29 * 38 17 16 15 14 13 30 * 37 36 35 34 33 32 31 * * 给出一个坐标,获得螺旋数字矩阵中的数值。(1 为点(0,0)正负方向为二维坐标轴方向) */ public class SpiralData { public static int getValueInSpiralMatrix(int x, int y) { if ((x >= 0) && (y >= 0) && (x == y)) {//第一象限对角线的情况,直接返回结果 return (2 * x + 1) * (2 * x + 1); }else if(Math.abs(x) >= Math.abs(y)){//x的绝对值大于y的绝对值的情况 if(x <= 0){//x在二三象限时,计算出左边x那列中间的数值根据y进行调整 return ((2 * Math.abs(x) + 1) * (2 * Math.abs(x) + 1) - (2 * Math.abs(x)) - (2 * Math.abs(x) + 1)/2) + y; }else{//x在一四象限时,计算出右边x那列中间的数值根据y进行调整 return ((2 * Math.abs(x) + 1) * (2 * Math.abs(x) + 1) - 3 * (2 * Math.abs(x)) - (2 * Math.abs(x) + 1)/2) - y; } }else{//x的绝对值小于y的绝对值的情况 if(y >= 0){//和上一种情况类似 return ((2 * Math.abs(y) + 1) * (2 * Math.abs(y) + 1) - (2 * Math.abs(y) + 1)/2) + x; }else{ return ((2 * Math.abs(y) + 1) * (2 * Math.abs(y) + 1) - 2 * (2 * Math.abs(y)) - (2 * Math.abs(y) + 1)/2) - x; } } } public static void main(String[] args) { for (int i = -3; i <= 3; i++) { for(int j = -3; j <= 3; j++) System.out.println(getValueInSpiralMatrix(i, j)); } } }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值