(大神勿入)据说是一道面试题,然后自己就写了一发(矩阵的螺旋输出)

给你一个n*m的矩阵,让你输出如下的数字矩阵:

01 06 05

02 03 04

如下截图:


就是这样,然后自己就写了一发:

代码贴出来供参考:

#include <stdio.h>
#define MAX 1000
using namespace std;
int maze[MAX][MAX];


int Update(int n,int m,int &sx,int &sy,int cnt,int sum)
{
    if(n==1&&m==1)
    {
        maze[sx][sy]=cnt++;
        return cnt;
    }
    for(int j=0;j<n;j++)
        maze[sx++][sy]=cnt++;
    if(cnt>sum)
        return cnt;
    sx--,sy++;
    for(int j=0;j<m-2;j++)
        maze[sx][sy++]=cnt++;
    if(cnt>sum)
        return cnt;
    for(int j=0;j<n;j++)
        maze[sx--][sy]=cnt++;
    if(cnt>sum)
        return cnt;
    sx++,sy--;
    for(int j=0;j<m-2;j++)
        maze[sx][sy--]=cnt++;
    return cnt;
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int cnt = 1;
        if(n==1)
        {
            for(int j=0;j<m;j++)
                maze[0][j]=cnt++;
        }
        else if(m==1)
        {
            for(int i=0;i<n;i++)
                maze[i][0]=cnt++;
        }
        else
        {
            int sx = 0,sy = 0;
            int tn = n, tm = m;
            while(cnt<=n*m)
            {
                cnt = Update(tn,tm,sx,sy,cnt,n*m);
                sx++;
                sy++;
                tn-=2;
                tm-=2;
            }
        }


        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                printf("%02d%c",maze[i][j],j==m-1?'\n':' ');
    }
    return 0;
}
 几组测试样例如下: 



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值