螺旋矩阵定义:螺旋矩阵是指一个呈螺旋状的矩阵,它的数字由第一行开始到右边不断变大,向下变大,向左变大,向上变大,如此循环。
坐标(4,3)对应的数字为34。
请定义一个函数,输入n,x,y(n为螺旋矩阵的阶数,x,y分别x轴、y轴坐标),返回n阶螺旋矩阵坐标(x,y)对应的数字。
#include<stdio.h>
#include<assert.h>
#define MIN(x, y) ({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void) (&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; })
int getPointValue(int n, int _x, int _y);
int main(){
int size = 0, x = 0, y = 0;
printf("Please input 3 integers as the size, x and y of a 2-dimension matrix.\n");
scanf(" %u %u %u", &size, &x, &y);
int result = getPointValue(size, x, y);
return 0;
}
int getPointValue(int n, int _x, int _y){
assert(_x >= 1 && _x <= n);
assert(_y >= 1 && _y <= n);
const int ulimit = n - 1, x = _x - 1, y = _y - 1;
int i, minIdx = -1, maxIdx = -1;
int sval = 0, result = 0;
minIdx = MIN( MIN(x, ulimit - x), MIN(y, ulimit - y) );
sval = 1;
for(i=0; i<minIdx; ++i){
sval += (ulimit - i * 2) * 4;
}
maxIdx = ulimit - minIdx;
if(y == minIdx){
result = sval + x - minIdx;
}
else if(x == maxIdx){
result = sval + (maxIdx - minIdx) + ( y - minIdx);
}
else if(y == maxIdx){
result = sval + (maxIdx - minIdx) * 2 + maxIdx - x;
}
else if (x == minIdx){
result = sval + (maxIdx - minIdx) * 3 + maxIdx - y;
}
else assert(0);
printf("f(%u,%u,%u)=%u\n", n, _x, _y, result);
return result;
}