题目是在《程序员面试宝典》(第一版)上看到的。
给出螺旋队列:
21 22 ...
20 07 08 09 10
19 06 01 02 11
18 05 04 03 12
17 16 15 14 13
实际输出的时候,01->1,以此类推。
以1为原点,右为x+,下为y+,给出坐标(m,n),输出该坐标上的数字。
思路:想明白之后会觉得非常简单。
首先求出目标坐标所在的正方形框的起点,然后用(数学里的)向量方法计算出移动步数,相加即可。
#include <iostream>
using namespace std;
int iABS(int mem) {
return (mem>=0 ? mem : (-1)*mem);
}
int roundSeq(int x, int y) {
int max = iABS(x + y + iABS(x - y));
int Rtn, Rtn_x, Rtn_y;
if(x + y >= 0) {
Rtn_x = max / 2;
Rtn_y = 1 - Rtn_x;
Rtn = (max - 1) * (max - 1) + 1;
Rtn += iABS(x-Rtn_x) + iABS(y-Rtn_y);
} else {
Rtn_x = max / 2;
Rtn_y = (-1) * Rtn_x;
Rtn = (max + 1) * (max + 1);
Rtn -= iABS(x-Rtn_x) + iABS(y-Rtn_y);
}
return Rtn;
}
int main()
{
int x, y;
while(cin >> x >> y) {
if(0 == x && 0 == y) { break; }
cout << roundSeq(x,y) << endl;
}
return 0;
}