1. 题目
给定一个螺旋矩阵,以(0,0)为原点,x轴向右为正,y轴向下为正,数值顺时针由内向外螺旋递增。编码实现输入任意一个坐标(x,y),输出对应的数值。
螺旋矩阵示例:
2. 思路
先观察矩阵数值规律,可发现:
- 数值从原点(0,0)处的1顺时针由内向外一圈圈递增。而且右上方对角线上的值为当前圈的最大值,第一圈为1,第二圈为9,第三圈为25,第四圈为49。由此可得出,设圈数为n,当前圈最大值为(2n-1)^2,即为右上角的值。
- 然后基于此,再分析x轴,y轴上取值与坐标的关系,可得出:
- 设 t = max(|x|,|y|)
- x轴正方向的值 v=(2t-1)^2+t
- y轴正方向的值 v=(2t-1)^2+3t
- x轴负方向的值 v=(2t-1)^2+5t
- y轴负方向的值 v=(2t-1)^2+7t
- 再扩散到坐标系四个象限的坐标位置,数值的计算:
- x == 0 && y == 0时,v=1
- |x| > |y|时:
- x>0时,v=(2t-1)^2+t+y
- x<0,v=(2t-1)^2+5t-y
- |x| <= |y|时:
- y>0,v=(2t-1)^2+3t-x
- y<0,v=(2t-1)^2+7t+x
3. 代码
public class SpiralMatrix {
// 螺旋矩阵坐标值计算
private static int spiralMatrix(int x, int y) {
if(x==0 && y==0){
return 1;
}
int abs_x = Math.abs(x);
int abs_y = Math.abs(y);
int t = Math.max(abs_x, abs_y);
int v = 0;
if(abs_x > abs_y){
if(x > 0){
v = (int) (Math.pow(2*t-1, 2) + t + y);
} else if (x < 0) {
v = (int) (Math.pow(2*t-1, 2) + 5*t - y);
}
}else{
if(y > 0){
v = (int) (Math.pow(2*t-1, 2) + 3*t - x);
} else if (y < 0) {
v = (int) (Math.pow(2*t-1, 2) + 7*t + x);
}
}
return v;
}
public static void main(String[] args) {
int x = -3, y = -1;
int v = spiralMatrix(x, y);
System.out.println("v="+v);
}
}