gpt4 book ai didi

c - 以螺旋方式打印二维数组的元素

转载 作者:行者123 更新时间:2023-11-30 16:59:31 25 4
gpt4 key购买 nike

我正在尝试以螺旋方式打印数组的元素..无法找出代码中的逻辑错误..

void spiral(int n,int m,int arr[][m])
{
int t=0,r=m-1,b=n-1,l=0,dir=0; /* t->top b->bottom l->left r->right */
int k,j;
// above parameters to manage the matrix.

// exit condition from loop
while (t<=b && l<=r)
{
// print top row
if (dir==0)
{

for (k=l;k<=r;k++)
{
printf("%d ",arr[t][k]);

}
dir=1;
t++;

}

// print right column
else if (dir==1)
{

for (k=t;k<=b;k++)
{
printf("%d ",arr[k][r]);

}
dir=2;
r--;

}

// print bottom row
else if (dir==2)
{

for (k=r;k>=l;k--)
{
printf("%d ",arr[b][k]);

}
dir=3;
b--;

}

// print left column
else if (dir==3)
{

for (k=b;k<=t;k--)
{
printf("%d ",arr[k][l]);

}
dir=0;
l++;

}
}
}

最佳答案

要完成任务,无需使用变量 dir并在所有步骤以相同顺序重复时检查其值。

最后一个循环的条件也有错误:k <= t应该是k >= t .

这是一个可能的工作实现:

void spiral(int n,int m,int arr[][m])
{
int top = 0,
right = m - 1,
bottom = n - 1,
left = 0,
k;

while( top <= bottom && left <= right )
{
//print top row
for ( k = left; k <= right; k++ )
{
printf("%d ",arr[top][k]);
}
++top;

//print right column
for( k = top; k <= bottom; k++ )
{
printf("%d ",arr[k][right]);
}
--right;

//print bottom row
for( k = right; k >= left; k-- )
{
printf("%d ",arr[bottom][k]);
}
--bottom;

//print left column
for( k = bottom; k >= top; k-- )
// this was wrong ^^^^^^ in OP's code
{
printf("%d ",arr[k][left]);
}
++left;
}
}

实例HERE

关于c - 以螺旋方式打印二维数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38086712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com