代码如下:
#include <iostream>
using namespace ::std;
int max(int n1, int n2)
{
return n1 > n2 ? n1 : n2;
}
int abs(int x)
{
return x > 0 ? x : -x;
}
int spiral(int x, int y) //根据坐标得出当前值
{
int c = max( abs(x), abs(y) ); //当前坐标所在圈
int max = ( c * 2 - 1 ) * ( c * 2 - 1 ); //上一圈的最大值
if( y == -c ) //上边
{
return max + 7*c + x;
}
else if( x == -c ) //左边
{
return max + 5*c - y;
}
else if( y == c ) //下边
{
return max + 3*c - x;
}
else //右边 (x == c)
{
return max + c + y;
}
}
void SpiralSeq( int n )
{
for( int i = -n; i <= n; ++i ) // y坐标
{
for( int j = -n; j <= n; ++j ) //x坐标
{
printf( "%5d", spiral( j, i ) );
//逆时针
//printf( "%5d", spiral( i, j ) );
}
printf("\n");
}
}
int main()
{
int n;
cout << "请输入顺时针螺旋队列的圈数:";
cin >> n;
SpiralSeq( n ); //打印矩阵
int x, y;
cout << "请输入横坐标:";
cin >> x;
cout << "请输入纵坐标:";
cin >> y;
cout << "值:" << spiral( x, y ) << endl;
system( "PAUSE");
return 0;
}
结果输出:
请输入顺时针螺旋队列的圈数:7
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
210 157 158 159 160 161 162 163 164 165 166 167 168 169 170
209 156 111 112 113 114 115 116 117 118 119 120 121 122 171
208 155 110 73 74 75 76 77 78 79 80 81 82 123 172
207 154 109 72 43 44 45 46 47 48 49 50 83 124 173
206 153 108 71 42 21 22 23 24 25 26 51 84 125 174
205 152 107 70 41 20 7 8 9 10 27 52 85 126 175
204 151 106 69 40 19 6 1 2 11 28 53 86 127 176
203 150 105 68 39 18 5 4 3 12 29 54 87 128 177
202 149 104 67 38 17 16 15 14 13 30 55 88 129 178
201 148 103 66 37 36 35 34 33 32 31 56 89 130 179
200 147 102 65 64 63 62 61 60 59 58 57 90 131 180
199 146 101 100 99 98 97 96 95 94 93 92 91 132 181
198 145 144 143 142 141 140 139 138 137 136 135 134 133 182
197 196 195 194 193 192 191 190 189 188 187 186 185 184 183
请输入横坐标:-3
请输入纵坐标:5
值:99
请按任意键继续. . .