一道AutoDesk笔试题

 要求是以螺旋形输出矩阵,例如:

输入:3

输出: 1 2 3   
              8 9 4   
              7 6 5 

思想:可以看作一群蚂蚁一直往前走,看到墙或者当前位置已经有蚂蚁时则转弯,转弯方向有4个,否则留一个蚂蚁。

 

#include  < iostream >
#include 
< iomanip >
#include 
< conio.h  >
using   namespace  std;
#define  MAXLENGTH 11

void  PrintPath( int  a[][MAXLENGTH], int  n)
{
    
int count=1;
    
int i=0;
    
int j=0;    
    
int direction=0;
    
while(count<=n*n)
    
{
        
if(a[i][j]==0&&i<MAXLENGTH&&j<MAXLENGTH)
        
{
            a[i][j]
=count;
            
if(direction==0)
            
{
                
if(j<MAXLENGTH-1&&a[i][j+1]==0)
                    j
++;
                count
++;
            }

            
else
            
if(direction==1)
            
{
                
if(i<MAXLENGTH-1&&a[i+1][j]==0)
                    i
++;
                count
++;
            }

            
else
            
if(direction==2)
            
{
                
if(j>0&&a[i][j-1]==0)
                    j
--;
                count
++;
            }

            
else
            
if(direction==3)
            
{
                
if(i>0&&a[i-1][j]==0)
                    i
--;
                count
++;
            }

        }

        
else
        
{
            direction
++;
            
if(direction>=4)
                direction
=direction%4;
            
if(direction==0)
            
{
                
if(j<MAXLENGTH-1)
                    j
++;
            }

            
else
            
if(direction==1)
            
{
                
if(i<MAXLENGTH-1)
                    i
++;
            }

            
else
            
if(direction==2)
            
{
                
if(j>0)
                    j
--;
            }

            
else
            
if(direction==3)
            
{
                
if(i>0)
                    i
--;
            }

        }

    }

}


void  Display( int  a[MAXLENGTH][MAXLENGTH])
{
    
int count=1;
    
for(int i=0;i<MAXLENGTH;i++)
    
{
        cout
<<endl;
        
for(int j=0;j<MAXLENGTH;j++)
        
{
            cout
<<setw(4)<<a[i][j]<<setw(4);
            
if(count%MAXLENGTH==0)
                cout
<<endl;
            count
++;
        }

    }

    printf(
" ");
}


void  main()
{
    
int a[MAXLENGTH][MAXLENGTH];
    
for(int i=0;i<MAXLENGTH;i++)
    
{
        
for(int j=0;j<MAXLENGTH;j++)
        
{
            a[i][j]
=0;
        }

    }

    PrintPath(a,MAXLENGTH);
    Display(a);
    getch();
}

 

              

你可能感兴趣的:(C/C++相关)