[ZJ]a417: 螺旋矩陣
題目:
http://zerojudge.tw/ShowProblem?problemid=a417
----------------------------------------------------------------------------------------------------
#include<bits/stdc++.h>
#define maxn 105
using namespace std;
int main(void)
{
int T,a[maxn][maxn];
scanf("%d",&T);
while(T --> 0)
{
int n,m,x,y,tot = 0;
scanf("%d%d",&n,&m);
memset(a,0,sizeof(a));
tot = a[x=0][y=0] = 1;
if(m == 1)
{
while(tot < n*n)
{
while(y+1<n && !a[x][y+1])
a[x][++y] = ++tot;
while(x+1<n && !a[x+1][y])
a[++x][y] = ++tot;
while(y-1>=0 && !a[x][y-1])
a[x][--y] = ++tot;
while(x-1>=0 && !a[x-1][y])
a[--x][y] = ++tot;
}
}
else
{
while(tot < n*n)
{
while(x+1<n && !a[x+1][y])
a[++x][y] = ++tot;
while(y+1<n && !a[x][y+1])
a[x][++y] = ++tot;
while(x-1>=0 && !a[x-1][y])
a[--x][y] = ++tot;
while(y-1>=0 && !a[x][y-1])
a[x][--y] = ++tot;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
printf("%5d",a[i][j]);
printf("\n");
}
}
return 0;
}
http://zerojudge.tw/ShowProblem?problemid=a417
----------------------------------------------------------------------------------------------------
#include<bits/stdc++.h>
#define maxn 105
using namespace std;
int main(void)
{
int T,a[maxn][maxn];
scanf("%d",&T);
while(T --> 0)
{
int n,m,x,y,tot = 0;
scanf("%d%d",&n,&m);
memset(a,0,sizeof(a));
tot = a[x=0][y=0] = 1;
if(m == 1)
{
while(tot < n*n)
{
while(y+1<n && !a[x][y+1])
a[x][++y] = ++tot;
while(x+1<n && !a[x+1][y])
a[++x][y] = ++tot;
while(y-1>=0 && !a[x][y-1])
a[x][--y] = ++tot;
while(x-1>=0 && !a[x-1][y])
a[--x][y] = ++tot;
}
}
else
{
while(tot < n*n)
{
while(x+1<n && !a[x+1][y])
a[++x][y] = ++tot;
while(y+1<n && !a[x][y+1])
a[x][++y] = ++tot;
while(x-1>=0 && !a[x-1][y])
a[--x][y] = ++tot;
while(y-1>=0 && !a[x][y-1])
a[x][--y] = ++tot;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
printf("%5d",a[i][j]);
printf("\n");
}
}
return 0;
}
留言
張貼留言