【每日面试题】矩阵的螺旋输出

         输入一个m*n的矩阵,将其螺旋输出,如下图:

代码如下:
//矩阵螺旋输出
#define max 100
int data[max][max]={0};
int Output(int m,int n,int &x,int &y,int cnt,int total)
{
	if(m==1&&n==1)
	{
        data[x][y]=cnt++;
		printf("%d\n",data[x][y]);
		return cnt;
	}
	for(int i=0;i<m;i++)
		data[x++][y]=cnt++;
	if(cnt>total)
		return cnt;
	x--;
	y++;
	for(int j=0;j<n-2;j++)
		data[x][y++]=cnt++;
	if(cnt>total)
		return cnt;
	for(int l=0;l<m;l++)
		data[x--][y]=cnt++;
    if(cnt>total)
		return cnt;
	x++;
	y--;
	for(int s=0;s<n-2;s++)
		data[x][y--]=cnt++;
	return cnt;
}


int main()
{
	int m=0,n=0;
	int cnt=1;
	scanf("%d%d",&m,&n);
    if(m>100||n>100)
	{
		printf("can't process\n");
		return -1;
	}
	if(m==0&&n==0)
		return -1;
	if(m==0)
	{
		for(int i=0;i<n;i++)
			data[m][i]=cnt++;
		for(int j=0;j<n;j++)
			printf("%d\n",data[m][j]);
		return 0;
	}
	else
		if(n==0)
		{
			for(int j=0;j<m;j++)
				data[j][n]=cnt++;
			for(int j=0;j<m;j++)
			printf("%d\t",data[j][n]);
			printf("\n");
		    return 0;
		}
		else
		{
			int x=0;
			int y=0;
			int i=m;
			int j=n;
	      while(cnt<=m*n)
	     {
	     	cnt=Output(i,j,x,y,cnt,m*n);
			i-=2;
			j-=2;
			x++;
			y++;
	       }  
		 
		}
		
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<n;j++)
				printf("%d\t",data[i][j]);
			printf("\n");
		}
	return 0;
}
以上是我理解的,希望有哪位大神能指点其他的高效算法!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值