順時針打印矩陣

題目
類型:數組 模擬
注意:cnt來統計,而且在四個操作中也要加,不然會出錯。

class Printer {
public:
    vector<int> clockwisePrint(vector<vector<int> > matrix, int m, int n) {
        if(!m) return {};
        if(m==1) return vector<int>(matrix[0].begin(), matrix[0].end());
        int left = 0, right = n-1, up = 0, down = m-1;
        int i = 0, j = 0, cnt = 0; 
        int N = m*n;
        vector<int> res;
        while(cnt < N){
            //向左
            while(cnt < N && j < right) res.push_back(matrix[i][j++]), cnt++;
            //向下
            while(cnt < N && i < down) res.push_back(matrix[i++][j]), cnt++;
            //向右
            while(cnt < N && j > left) res.push_back(matrix[i][j--]), cnt++;
            //向上
            while(cnt < N && i > up) res.push_back(matrix[i--][j]), cnt++;
            //更新四個邊界
            i++, j++;
            up++, down--, left++, right--;
            if(res.size() == N - 1) res.push_back(matrix[i][j]), cnt++;
        }
        
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章