您的位置:首页 > 职场人生

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

2012-04-17 09:46 411 查看
给你一个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;
}


几组测试样例如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试 ini 测试 c