sicily 1694 Spiral 蛇形矩阵
题目给出蛇形矩阵,要求计算给定的值在蛇形矩阵的位置。
注意到,矩阵的右上角的值是某个奇数的平方,从内到外依次是1,3,5…的平方。先求出要求的数对应的右上角的数的坐标,再根据与距离来计算指定数的坐标
#include <iostream> #include <cstdio> using namespace std; int n, m; void find() { int place_zero = n/2+1; int len = 1, right_up= 1; int s = 1; //计算右上角的值 while (right_up < m) { len = 2*s + 1; right_up = len*len; s++; } int cnt; int x, y; //计算右上角的值 x = place_zero - (len-1)/2; y = place_zero + (len-1)/2; cnt = right_up - m; //计算与右上角的值距离 if (cnt >= 0 && cnt < len) //上边 y = y - cnt; else if (cnt >= len && cnt <= 2*(len-1)) //左边 { y = y - (len - 1); x = x + cnt - len + 1; } else if (cnt > 2*(len-1) && cnt <= 3*(len-1)) //下边 { x = x + len - 1; y = y - (len - 1) + cnt - 2*(len-1); } else x = x + len - 1 - (cnt - 3*(len-1)); //右边 printf("%d %d\n", x, y); } int main() { int cases; scanf("%d", &cases); while (cases--) { scanf("%d%d", &n, &m); find(); } return 0; }