题目如下
===========
43 44 45 46 47 .. ..
42 21 22 23 24 25 26
41 20 07 08 09 10 27
40 19 06 01 02 11 28
39 18 05 04 03 12 29
38 17 16 15 14 13 30
37 36 35 34 33 32 31
看清以上数字排列的规律, 设1点的坐标是(0,0), x方向向右为正, y方向向下为正. 例如, 7的坐标为(-1,-1), 2的坐标为(0,1), 3的坐标为(1,1). 编程实现输入任意点的坐标, 输出所对应的数字.
===========
我自己做的答案贴在下面. 在VC上调试通过.
标准答案还没看, 太晚了. 改天再研究一下贴上来吧.
#include <iostream> #include <cmath> using namespace std; int iMatrix[100][100]; void FillEdge(int width, int layer) { // Up right corner int temp = iMatrix[layer][width - 1 - layer] = (width - layer - layer) * (width - layer -layer); // Up edge for( int i = width - 1 - layer; i >= layer; --i) iMatrix[layer][i] = temp--; // Left edge for( int j = 1 + layer; j < width - layer; ++j) iMatrix[j][layer] = temp--; // Low edge for( int i = 1 + layer; i < width - layer; ++i) iMatrix[width - 1 - layer][i] = temp--; // Right edge for( int j = width - 2 - layer; j > layer; --j) iMatrix[j][width - 1 - layer] = temp--; } void Print(int width) { for(int i = 0; i < width; i++) { for(int j = 0; j < width; j++) { cout<<iMatrix[i][j]<<"\t"; } cout<<endl; } cout<<endl; } int main() { memset(iMatrix, 0, sizeof(iMatrix)); cout << "螺旋数组" << endl; int x = 0; int y = 0; cin >> x; cin >> y; int iBigger = 0; if(abs(x) >= abs(y)) iBigger = abs(x); else iBigger = abs(y); int width = 2 * iBigger + 1; for(int w = 0; w <= iBigger; w++) { FillEdge(width, w); } Print(width); cout<<iMatrix[y + iBigger][x + iBigger]; }
题目来源:
<程序员面试宝典>