首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

法则数组的打印

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

规律数组的打印
规律数组的打印

【北京直真笔试题】打印数组如下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[思想:层层剥离.]

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} //printArrayvoid 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--)                  {                        nArray[j][g_nCnt-i-1] = nBase++;                   }                    for(int j = g_nCnt-i-2; j > i; j--)                   {                           nArray[i][j]= nBase++;                   }                   if(nSize%2 == 1)                   {                            nArray[nSize/2][nSize/2] = nBase; //N为奇数,最后元素的处理.                       }         }//end for i}

     [运行结果]:

       法则数组的打印

        或者大家还有什么好的思路,欢迎交流探讨!

热点排行