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)); } } }