读书人

输出循环队列.

发布时间: 2012-04-10 21:03:56 作者: rapoo

输出循环队列...求助
21 22 ....
21 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13


想了半天没思路,,求指导

[解决办法]
蛇形矩阵.

一开始是走1步1拐,拐2次之后,就变成了2步1拐,自己算算.
[解决办法]

C/C++ code
#include <stdio.h>#include <stdlib.h>#include <math.h>#define TABLE_ROW 100#define TABLE_COL TABLE_ROWstatic int aTable[TABLE_ROW][TABLE_COL]={0};static int aDirect[4][2]={    {0,1},{1,0},{0,-1},{-1,0}};/*21 22 ....21 7 8 9 1019 6 1 2 1118 5 4 3 1217 16 15 14 13*/int main(){    int iRow,iCol,iNum;    int iStep,iCntStep;    int iDir,iCntDir;    int iTopRow=-1,iTopCol=TABLE_COL,iBotRow,iRightCol=-1;    scanf("%d",&iNum);    iRow=iCol=(int)sqrt(1.0*iNum);        iStep=1;    iCntStep=iDir=iCntDir=0;    for(int iCnt=0;iCnt!=iNum;++iCnt)    {        aTable[iRow][iCol]=iCnt+1;        if(iCntStep==iStep)        {            //change direction            iDir=(iDir+1)%4;            iCntStep=0;            iCntDir++;            if(iCntDir==2)            {                iCntDir=0;                iStep++;            }        }        iCntStep++;        iRow+=aDirect[iDir][0];        iCol+=aDirect[iDir][1];    }    //找打印范围    for(int iR=0;iR<TABLE_ROW;++iR)    {        bool bHas=false;        for(int iC=0;iC<TABLE_COL;++iC)        {            if(aTable[iR][iC]!=0)            {                    bHas=true;                iBotRow=iR;        //最低行                if(iTopRow==-1)                {                    iTopRow=iR;    //最高行                }                if(iC<iTopCol)                {                    iTopCol=iC;    //最左列                }            }            else if(aTable[iR][iC]==0 && bHas)            {                if(iC>iRightCol)                {                    iRightCol=iC;                }                break;            }        }    }    for(int iR=iTopRow;iR<=iBotRow;++iR)    {        bool bPrtLn=false;        for(int iC=iTopCol;iC<iRightCol;++iC)        {            if(aTable[iR][iC]==0)            {                printf("   ");            }            else            {                bPrtLn=true;                printf("%3d",aTable[iR][iC]);            }        }        if(bPrtLn)        {            printf("\n");        }        else        {            break;        }    }    return 0;}79 73 74 75 76 77 78 79 72 43 44 45 46 47 48 49 50 71 42 21 22 23 24 25 26 51 70 41 20  7  8  9 10 27 52 69 40 19  6  1  2 11 28 53 68 39 18  5  4  3 12 29 54 67 38 17 16 15 14 13 30 55 66 37 36 35 34 33 32 31 56 65 64 63 62 61 60 59 58 57请按任意键继续. . . 

读书人网 >C语言

热点推荐