当前位置:编程学习 > C/C++ >>

规律数组的打印

规律数组的打印
【北京直真笔试题】打印数组如下4*4数组,要求打印N*N的数组?

1  12  11  10

2  13  16  9

3  14  15  8

4   5   6  7

【思路】:

 


1.发现规律;如上图所示,仔细发现是有规律的,先第1、2、3、4步骤;我们发现第5、6、7…步骤和前面的1、2、3、4步骤是相同的,只是边界值不同。

2.考虑实现;实现的问题转换为先定义二维数组,数组的元素为0.然后的操作就是填值的过程。边界值的确定采用层层剥离的思想。我们容易看出循环的次数正是N/2次。存在当N为奇数时需要单独处理最后一个数的情况。

 【算法实现】:

//design[思想:层层剥离.]

[cpp] 
void designArray(int nArray[][g_nCnt], int nSize) 

        int nBase = 1; 
         for(int i = 0; i < g_nCnt/2; i++) 
         { 
                  for(int j = i; j < g_nCnt-i; j++) 
                   { 
                           nArray[i][j] = nBase++; 
                   } 
 
                   for(int j = i+1; j < g_nCnt-i; j++) 
                   { 
                            nArray[j][g_nCnt-i-1] = nBase++; 
                   } 
 
                   for(int j = g_nCnt-i-2; j >= i; j--) 
                   { 
                            nArray[g_nCnt-i-1][j] = nBase++; 
                   } 
 
                   for(int j = g_nCnt-i-2; j > i; j--) 
                   { 
                            nArray[j][i] = nBase++; 
                   } 
 
                   if(nSize%2 == 1) 
                   { 
                           nArray[nSize/2][nSize/2] = nBase; 
                   } 
         }//end for i 

 
  
 
//printArray 
void printArray(int nArray[][g_nCnt], int nSize) 

        static int s_nCnt = 0; 
         cout << "----------------------DESIGN " << ++s_nCnt ; 
         cout << "----------------------"  << endl; 
         for(int i=0; i <nSize; i++) 
         { 
                  for(int j =0; j < nSize; j++) 
                   { 
                      cout << nArray[i][j] << "\t"; 
                   }//end for j 
                   cout << endl; 
         }//end for i 
         cout << "----------------------\\DESIGN " << s_nCnt ; 
         cout << "----------------------"  << endl;  
         cout << endl << endl; 

 
  
 
  
 
void designArray_t(int nArray[][g_nCnt], int nSize) 

         int nBase = 1; 
         for(int i = 0; i < g_nCnt/2; i++) 
         { 
                   for(int j = i; j < g_nCnt-i; j++) 
                  { 
                       nArray[j][i] = nBase++; 
                   } 
 
                   for(int j = i+1; j < g_nCnt-i; j++) 
                   { 
                       nArray[g_nCnt-i-1][j] = nBase++; 
                   } 
 
                  for(int j = g_nCnt-i-2; j >= i; j--) 
                  { 
               &nb

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,