1. 程式人生 > >劍指Offer(29):順時針列印矩陣

劍指Offer(29):順時針列印矩陣

題目

  • 輸入一個矩陣,按照從外向裡以順時針的順序依次打印出每個數字,例如,如果輸入如下矩陣:

在這裡插入圖片描述


則依次打印出陣列:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10。

  1. 思路

    將結果存放在vector 陣列中,從左到右,再從上到下,再從右到左,最後從下到上遍歷。

  2. 思考:

  • 遍歷停止的標誌是什麼
  • 邊界必須非常清晰的控制好! 考察邊界控制能力!

程式碼:

vector<int> printMatrix(vector<vector<int> > matrix)
{
    vector<int> result;
    int rows = matrix.size();
    int cols = matrix[0].size();

    if(rows == 0 && cols == 0)
    {
        return result;
    }
    int left = 0, right = cols - 1, top = 0, bottom = rows - 1;

    while(left <= right && top <= bottom)
    {
        //from left to right
        for(int i = left; i <= right; ++i)
        {
            result.push_back(matrix[top][i]);
        }
        //from top to bottom
        for(int i = top + 1; i <= bottom; ++i)
        {
            result.push_back(matrix[i][right]);
        }
        //from right to left
        if(top != bottom)
        {
            for(int i = right - 1; i >=left; --i)
            {
                result.push_back(matrix[bottom][i]);
            }
        }
        //from bottom to top
        if(left != right)
        {
            for(int i = bottom -1; i > top; --i)
            {
                result.push_back(matrix[i][left]);
            }
        }
        left++, top++, right--, bottom;
    }
    return result;
}
  • 程式碼思路比較清晰,要注意特殊情況,例如最後只剩下一束或一橫可走,那麼,只剩一下一束,則不用再走from bottom to top!!! 而這剩下一束的標誌是,right == bottom!!! 同理,只剩下一橫,則不用再走from right to left!!! 而剩下 一橫的標誌是 top= bottom!!!!