#每日一題#2016騰訊實習生筆試題

       題目:蛇形矩陣

            題目的大意是這樣:

                 輸入2

                矩陣爲:
                 1    2

                 4    3

                 輸出:1 2 4 3 //按行打印

                 輸入:3

                 矩陣爲:

                 1   2    3

                 8   9    4

                 7   6    5

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

       下面給出具體的代碼:


#include<iostream>
#include<vector>
using namespace std;
void fun(const int n)
{
    vector<int> elem;
    elem.resize(n);
    vector<vector<int> >array(n,elem);
    int count = 0;
    int topleft[2] = {0,0};
    int topright[2] = {0,n - 1};
    int bottomleft[2] = {n - 1,0};
    int bottomright[2] = {n - 1,n - 1};
    int col = 0,row = 0;
    int i = 0, j = 0;
    while(true){
        row = topleft[0];
        col = topleft[1];
        while(col <= topright[1]){
            array[row][col++] = ++count;
        }
        topright[1] -= 1;
        topright[0] += 1;
    
        row = topright[0];
        col = topright[1] + 1;
        while(row <= bottomright[0]){
            array[row++][col] = ++count;
        }
        bottomright[0] -= 1;
        bottomright[1] -= 1;

        col = bottomright[1];
        row = bottomright[0] + 1;
        while(col >= bottomleft[1]){
            array[row][col--] = ++count;
        }
        
        bottomleft[0] -= 1;
        bottomleft[1] += 1;

        row = bottomleft[0];
        col = bottomleft[1] - 1;
        while(row > topleft[0]){
            array[row--][col] = ++count;
        }

        topleft[0] += 1;
        topleft[1] += 1;
        if(topleft[1] >= topright[1]){
            if(n % 2 != 0){
                array[n / 2][n / 2] = ++count;
            }
            break;
        }
    }
    for(i = 0;i < n; i++){
        for(j = 0;j < n;j++){
            cout << array[i][j] <<"  ";
        }
        cout << endl;
    }
}
int main(int argc,char**argv)
{
    int n = 0;
    cin>>n;
    fun(n);
    return 0;
}

程序的執行結果:

該程序需要判斷n的奇偶,當n爲奇數時,在矩陣的最中間還要放一個數,當n爲偶數時,則不用放。

下面給出一種比較簡便的方法:

void fun1(const int n)
{
    int i,j,k;
    int array[n][n];
    int cnt = 0;
    for(k = 0; k < n / 2;k++){
        i = k;
        for(j = k;j < n - 1 - k;j++){
            array[i][j] = ++cnt;
        }
        for(;i < n - 1 - k;i++){
            array[i][j] = ++cnt;
        }
        for(;j > k;j--){
            array[i][j] = ++cnt;
        }
        for(;i > k;i--){
            array[i][j] = ++cnt;
        }
    }
    if(n % 2){
        array[n / 2][n / 2] = ++cnt;
    }
    for(i = 0;i < n; i++){
        for(j = 0;j < n;j++){
            cout << array[i][j] <<"  ";
        }
        cout << endl;
    }

}

其執行結果是和上面的一模一樣的。。。

該思路就是一圈一圈的進行打印,所以大的循環要進行n/2次,因爲有n/2個大圈,每個大圈又分爲向右打印,向下打印,向左打印,向上打印,打印時要注意:把角上的元素放在下一次打印的首個元素,這樣可以起到過渡的作用。。。

第一種方法應該是官方給出的答案,個人認爲第二種方法比較好大笑大笑大笑。。。。

發佈了65 篇原創文章 · 獲贊 19 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章