WA了好久,注释部分不知道怎么错了,记录4条边的输出长度。
后来改了,用i,j表示计算到的位置,把输出了的值赋值成-1,就能判断边界了,然后就循环就行了。
#include<cstdio>
#include<cstring>
int m[1111][1111];
int mm,n;
int main()
{
while(scanf("%d%d",&n,&mm) != EOF)
{
if(n <= 0 && m <= 0)
{
continue;
}
for(int i=0;i<n;++i)
{
for(int j=0;j<mm;++j)
{
scanf("%d",&m[i][j]);
}
}
/* if(n == 1 || mm == 1)
{
for(int i=0;i<n;++i)
{
for(int j=0;j<mm;++j)
{
if(i == 0 && j == 0)
printf("%d",m[i][j]);
else
printf(" %d",m[i][j]);
}
}
printf("\n");
continue;
}
int count = 0;
int upleft,upright,leftup,leftdown,downleft,downright,rightup,rightdown;
upleft = 0 ,upright = mm-1;
leftup = 1 ,leftdown = n-2;
downleft = 0,downright = mm-2;
rightup = 1,rightdown = n-1;
while(count < n*mm)
{
if(upleft <= upright)
{
for(int i=upleft;i<=upright;++i)
{
if(count == 0)
printf("%d",m[leftup-1][i]);
else
printf(" %d",m[leftup-1][i]);
count++;
}
upleft++,upright--;
}
if(rightup <= rightdown)
{
for(int i=rightup;i<=rightdown;++i)
{
printf(" %d",m[i][upright+1]);
count++;
}
rightup++,rightdown--;
}
if(downleft <= downright)
{
for(int i=downright;i>=downleft;--i)
{
printf(" %d",m[rightdown+1][i]);
count++;
}
downleft++,downright--;
}
if(leftup <= leftdown)
{
for(int i=leftdown;i>=leftup;--i)
{
printf(" %d",m[i][upleft-1]);
count++;
}
leftup++,leftdown--;
}
}*/
int count = 0;
int i = 0,j = 0;
while(count < n*mm)
{
while(j<mm && m[i][j] != -1)
{
printf("%d ",m[i][j]);
m[i][j] = -1;
j++;
count++;
}
j--;
i++;
while(i<n && m[i][j] != -1)
{
printf("%d ",m[i][j]);
m[i][j] = -1;
i++;
count++;
}
i--;
j--;
while(j >= 0 && m[i][j] != -1)
{
printf("%d ",m[i][j]);
m[i][j] = -1;
j--;
count++;
}
j++;
i--;
while(i >= 0 && m[i][j] != -1)
{
printf( "%d ",m[i][j]);
m[i][j] = -1;
i--;
count++;
}
i++;
j++;
}
printf("\n");
}
return 0;
}