日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 1030. 距离顺序排列矩阵单元格(排序Lambda表达式BFS)

發布時間:2024/7/5 编程问答 111 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 1030. 距离顺序排列矩阵单元格(排序Lambda表达式BFS) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 1. 題目
    • 2. 解題
      • 2.1 multimap
      • 2.2 Lambda 表達式排序
      • 2.3 BFS搜索

1. 題目

給出 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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/matrix-cells-in-distance-order
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. 解題

2.1 multimap

  • 利用其有序性,用距離作為key,vector 作為 value
class Solution { public:vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {vector<vector<int>> ans;multimap<int,vector<int>> m;int i, j, k = 0;for(i = 0; i < R; ++i){for(j = 0; j < C; ++j)m.emplace(pair<int,vector<int>> (abs(i-r0)+abs(j-c0),vector<int> ({i,j})));}for(auto& kv : m)ans.push_back(kv.second);//可以把多個vector<int>一起push進去,神奇return ans;} };

2.2 Lambda 表達式排序

class Solution { public:vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {vector<vector<int>> ans(R*C);int i, j, k = 0;for(i = 0; i < R; ++i)for(j = 0; j < C; ++j)ans[k++] = {i,j};//[&],里面的&表示表示式所在區域的外部變量可見,且是引用傳遞,之前沒寫,報錯sort(ans.begin(), ans.end(), [&](auto& a, auto& b){return abs(a[0]-r0)+abs(a[1]-c0) < abs(b[0]-r0)+abs(b[1]-c0);});return ans;} };

2.3 BFS搜索

class Solution {vector<vector<int>> dir = {{1,0},{0,1},{0,-1},{-1,0}}; public:vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {vector<vector<int>> ans(R*C);bool visited[R][C];memset(visited, 0, sizeof visited);queue<pair<int,int>> q;pair<int,int> tp;q.push({r0,c0});visited[r0][c0] = true;int x, y, k, i = 0;while(!q.empty()){tp = q.front();q.pop();ans[i++] = {tp.first, tp.second};for(k = 0; k < 4; ++k){x = tp.first + dir[k][0];y = tp.second + dir[k][1];if(x>=0 && x<R && y>=0 && y<C && !visited[x][y]){q.push({x,y});visited[x][y] = true;}}}return ans;} };

總結

以上是生活随笔為你收集整理的LeetCode 1030. 距离顺序排列矩阵单元格(排序Lambda表达式BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。