順時針打印矩陣

題目見此鏈接
簡單說一下思路:打印總共可分爲四部,從左往右,從上到下,從右往左,從下到上。執行完這四步後,相當於對原矩陣剝了一層皮,可看成一個新的待打印矩陣。然後重複執行上述四步

class Solution {
public:
    //如果只是輸出打印數字的話,用遞歸方式更好
    vector<int> printMatrix(vector<vector<int> > matrix) {
        int Col = matrix[0].size();//矩陣有多少列
        int Row = matrix.size();//矩陣有多少行
        vector<int>result;//輸出矩陣
        //下標
        int index_row = 0;
        int index_col = 0;
        int circleCount = 1;//計算打印的圈數
        //空矩陣
        if(Col == 0 || Col == 0)
            return result;
        //矩陣存在且至少有兩行兩列
        while(index_row < Row - 1 && index_col < Col - 1)
        {
            //打印從左往右的數據
            for(;index_col < Col - 1;index_col ++)
            {
                result.push_back(matrix[index_row][index_col]);
            }
            //打印從上往下的數據
            for(;index_row < Row - 1;index_row ++)
            {
                result.push_back(matrix[index_row][index_col]);
            }
            //打印從右往左的數據
            for(;index_col >= circleCount; index_col --)
            {
                result.push_back(matrix[index_row][index_col]);
            }
            for(;index_row >= circleCount ; index_row --)
            {
                result.push_back(matrix[index_row][index_col]);
            }
            index_row ++;
            index_col ++;
            Col --;
            Row --;
            circleCount ++;
        }
        //處理只有一行(列)的情況
        if(Col - 1 == index_col)//唯一列
        {
            for(;index_row < Row;index_row ++)
            {
                result.push_back(matrix[index_row][index_col]);
            }
            return result;

        }else if(Row - 1 == index_row)//唯一行
        {
            for(;index_col < Col;index_col ++)
            {
                result.push_back(matrix[index_row][index_col]);
            }
            return result;
        }else//此時爲空
            return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章