螺旋队列问题
从外到里螺旋,以1点的坐标为(0,0),x右为正,y向下为正,建立坐标轴。编程实现任意输入一点坐标(x,y),输出对应的数字。
第一层为2-9
第二层为10-25
第三层为26-36
所以在坐标轴上有四种情况:
- 向右:x==t,即(y==0),数值(2t-1)^2+t;v=(2t-1)^2+t+y;
- 向左:x==-t,即(y==0),数值(2t-1)^2+5t;v=(2t-1)^2+5t-y;
- 向下:y==t,即(x==0),数值(2t-1)^2+3t;v=(2t-1)^2+3t-x;
- 向上:y==-t,即(x==0),数值(2t-1)^2+7t;v=(2t-1)^2+7t+x
1 #include <iostream> 2 #include <stdio.h> 3 #include <string> 4 #include <algorithm> 5 #include <vector> 6 7 #define max(a,b) ((a)<(b)?(b):(a)) 8 #define abs(a) ((a)>0?(a):-(a)) 9 10 using namespace std; 11 12 //内循环螺旋队列问题 13 int foo(int x, int y) 14 { 15 int t = max(abs(x), abs(y)); 16 int u = t + t; 17 int v = u - 1; 18 v = v*v + u; 19 if (x == -t) 20 { 21 v += u + t - y; 22 } 23 else if (y == -t) 24 v += 3 * u + x - t; 25 else if (y == t) 26 v += t - x; 27 else 28 v += y - t; 29 30 return v; 31 } 32 33 int main() 34 { 35 int x, y; 36 for (y = -4; y <= 4; y++) 37 { 38 for (x = -4; x <= 4; x++) 39 { 40 printf("%5d", foo(x, y)); 41 } 42 printf("\n"); 43 } 44 while (scanf_s("%d%d", &x, &y) == 2) 45 { 46 printf("%d\n", foo(x, y)); 47 } 48 system("pause"); 49 return 0; 50 }
1 #include <iostream> 2 #include <stdio.h> 3 #include <string> 4 #include <algorithm> 5 #include <vector> 6 7 using namespace std; 8 int a[10][10]; 9 void Fun(int n) 10 { 11 int m = 1, j, i; 12 for (i = 0; i < n / 2; i++) { 13 for (j = 0; j < n - i; j++) { 14 if (a[i][j] == 0) 15 a[i][j] = m++; 16 } 17 for (j = i + 1; j < n - i; j++) 18 { 19 if (a[j][n - 1 - i] == 0) 20 a[j][n - 1 - i] = m++; 21 } 22 for (j = n - 1 - i; j > i; j--) 23 { 24 if (a[n - i - 1][j] == 0) 25 a[n - i - 1][j] = m++; 26 } 27 for (j = n - 1 - i; j > i; j--) 28 { 29 if (a[j][i] == 0) 30 a[j][i] = m++; 31 } 32 } 33 if (n % 2 == 1) 34 a[n / 2][n / 2] = m; 35 } 36 37 int main() 38 { 39 int n, i, j; 40 cin >> n; 41 for (int i = 0; i < n; i++) 42 { 43 for (int j = 0; j < n; j++) 44 a[i][j] = 0; 45 } 46 Fun(n); 47 for (i = 0; i < n; i++) 48 { 49 for (j = 0; j < n; j++) 50 { 51 cout<< a[i][j] << " "; 52 } 53 cout << endl; 54 } 55 system("pause"); 56 return 0; 57 }
转载请说明出处!