天天看點

規律數組的列印

【北京直真筆試題】列印數組如下44數組,要求列印NN的數組?

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
}
 
 
 
//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--)
                  {
                        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
}           

[運作結果]:

規律數組的列印

或者大家還有什麼好的思路,歡迎交流探讨!

繼續閱讀