Leetcode 1030. 距離順序排列矩陣單元格 1030. Matrix Cells in Distance Order

1030. 距離順序排列矩陣單元格
給出 R 行 C 列的矩陣,其中的單元格的整數座標爲 (r, c),滿足 0 <= r < R 且 0 <= c < C。
另外,我們在該矩陣中給出了一個座標爲 (r0, c0) 的單元格。
返回矩陣中的所有單元格的座標,並按到 (r0, c0) 的距離從最小到最大的順序排,其中,兩單元格(r1, c1) 和 (r2, c2) 之間的距離是曼哈頓距離,|r1 - r2| + |c1 - c2|。(你可以按任何滿足此條件的順序返回答案。)

示例 1:

輸入:R = 1, C = 2, r0 = 0, c0 = 0
輸出:[[0,0],[0,1]]
解釋:從 (r0, c0) 到其他單元格的距離爲:[0,1]
示例 2:

輸入:R = 2, C = 2, r0 = 0, c0 = 1
輸出:[[0,1],[0,0],[1,1],[1,0]]
解釋:從 (r0, c0) 到其他單元格的距離爲:[0,1,1,2]
[[0,1],[1,1],[0,0],[1,0]] 也會被視作正確答案。
示例 3:

輸入:R = 2, C = 3, r0 = 1, c0 = 2
輸出:[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
解釋:從 (r0, c0) 到其他單元格的距離爲:[0,1,1,2,2,3]
其他滿足題目要求的答案也會被視爲正確,例如 [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]。

提示:

1 <= R <= 100
1 <= C <= 100
0 <= r0 < R
0 <= c0 < C

執行用時 : 192 ms, 在Matrix Cells in Distance Order的C++提交中擊敗了73.97% 的用戶
內存消耗 : 27.6 MB, 在Matrix Cells in Distance Order的C++提交中擊敗了100.00% 的用戶
class Solution {
public:
    vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
        multimap<int,vector<int>> m;  //multimap 不會去重
        vector<vector<int>> res;
        vector<int> temp(2);          //map的value是個vector向量長度爲2
        for(int i=0;i<R;i++){
            for(int j=0;j<C;j++){
                temp[0]=i,temp[1]=j;
                m.insert(make_pair(abs(i-r0)+abs(j-c0),temp)); //使用距離做key,輸出做value
            }                                                  //map會自動排序
        }
        auto it = m.begin();
        for(;it != m.end();it++){
            res.push_back(it->second);
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章