您的位置:首页 > 其它

脑洞脑洞 螺旋矩阵

2017-08-03 10:33 211 查看
由内向外扩散的螺旋矩阵:

int getv(int x, int y, int n) //螺旋矩阵(由内向外扩散)
{
int t = (n - 1) | 1;
if (x <= y) {
int k = min(x, t - y);
return (t - 2 * k) * (t - 2 * k - 1) + 1 + (x + y - 2 * k);
}
int k = min(y + 1, t - x) - 1;
return (t - 2 * k) * (t - 2 * k - 1) + 1 - (x + y - 2 * k);
}

由外向内的螺旋矩阵:
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;

#define pi acos(-1)
#define endl '\n'
#define srand() srand(time(0));
#define me(x,y) memset(x,y,sizeof(x));
#define foreach(it,a) for(__typeof((a).begin()) it=(a).begin();it!=(a).end();it++)
#define close() ios::sync_with_stdio(0); cin.tie(0);
#define FOR(x,n,i) for(int i=x;i<=n;i++)
#define FOr(x,n,i) for(int i=x;i<n;i++)
#define W while
#define sgn(x) ((x) < 0 ? -1 : (x) > 0)
#define bug printf("***********\n");
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL LINF=0x3f3f3f3f3f3f3f3fLL;
const int dx[]={-1,0,1,0,1,-1,-1,1};
const int dy[]={0,1,0,-1,-1,1,-1,1};
const int maxn=1000;
const int maxx=1e7+100;
const double EPS=1e-7;
const int MOD=10000007;
#define mod(x) ((x)%MOD);
template<class T>inline T min(T a,T b,T c) { return min(min(a,b),c);}
template<class T>inline T max(T a,T b,T c) { return max(max(a,b),c);}
template<class T>inline T min(T a,T b,T c,T d) { return min(min(a,b),min(c,d));}
template<class T>inline T max(T a,T b,T c,T d) { return max(max(a,b),max(c,d));}
inline int Scan()
{
int Res=0,ch,Flag=0;
if((ch=getchar())=='-')Flag=1;
else if(ch>='0' && ch<='9')Res=ch-'0';
while((ch=getchar())>='0'&&ch<='9')Res=Res*10+ch-'0';
return Flag ? -Res : Res;
}
//freopen( "in.txt" , "r" , stdin );
//freopen( "data.out" , "w" , stdout );
//cerr << "run time is " << clock() << endl;

int n,x,y;
int check(int x0,int y0)
{
if(x0==x&&y0==y)
return 1;
return 0;
}
void solve()
{
while(~scanf("%d%d%d",&n,&x,&y))
{
int tot=1,xx=1,yy=0,flag=0;
int l=1,r=n,d=n,u=1;
while(tot<n*n&&!flag)
{
while(yy<r) {++yy,++tot;if(check(xx,yy)) {flag=1;break;}}--r;
if(flag) break;
while(xx<d) {++xx,++tot;if(check(xx,yy)) {flag=1;break;}}--d;
if(flag) break;
while(yy>l) {--yy,++tot;if(check(xx,yy)) {flag=1;break;}}++l;
if(flag) break;
while(xx>u+1) {--xx,++tot;if(check(xx,yy)) {flag=1;break;}}++u;
if(flag) break;
}
cout<<tot<<endl;
}
}
int main()
{
solve();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: