鱼C论坛

 找回密码
 立即注册
查看: 914|回复: 0

[技术交流] C++刷leetcode(1162. 地图分析)【广度优先搜索】【图】

[复制链接]
发表于 2020-6-2 12:06:04 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 你现在手里有一份大小为 N x N 的「地图」(网格) grid,上面的每个「区域」(单元格)都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,请你找出一个海洋区域,这个海洋区域到离它最近的陆地区域的距离是最大的。

  2. 我们这里说的距离是「曼哈顿距离」( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个区域之间的距离是 |x0 - x1| + |y0 - y1| 。

  3. 如果我们的地图上只有陆地或者海洋,请返回 -1。

  4.  

  5. 示例 1:



  6. 输入:[[1,0,1],[0,0,0],[1,0,1]]
  7. 输出:2
  8. 解释:
  9. 海洋区域 (1, 1) 和所有陆地区域之间的距离都达到最大,最大距离为 2。
  10. 示例 2:



  11. 输入:[[1,0,0],[0,0,0],[0,0,0]]
  12. 输出:4
  13. 解释:
  14. 海洋区域 (2, 2) 和所有陆地区域之间的距离都达到最大,最大距离为 4。
  15.  

  16. 提示:

  17. 1 <= grid.length == grid[0].length&#160;<= 100
  18. grid[i][j]&#160;不是&#160;0&#160;就是&#160;1

  19. 来源:力扣(LeetCode)
  20. 链接:https://leetcode-cn.com/problems/as-far-from-land-as-possible
  21. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. class Solution {
  2. public:
  3.     int maxDistance(vector<vector<int>>& grid) {
  4.         //广度优先搜索
  5.         //构建方向矩阵
  6.         vector<vector<int> > direct = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
  7.         //构建queue
  8.         int len1 = grid.size(), len2 = grid[0].size();
  9.         queue<pair<int, int> > temp;
  10.         for(int i = 0; i < len1; i++){
  11.             for(int j = 0; j < len2; j++){
  12.                 if(grid[i][j] == 1){
  13.                     temp.push(make_pair(i, j));
  14.                     grid[i][j] = 2;
  15.                 }
  16.             }
  17.         }
  18.         int res = -1;
  19.         while(!temp.empty()){
  20.             int len = temp.size();
  21.             res++;
  22.             for(int i = 0; i < len; i++){
  23.                 pair<int, int> store = temp.front();
  24.                 temp.pop();
  25.                 for(auto cha : direct){
  26.                     int x = store.first + cha[0];
  27.                     int y = store.second + cha[1];
  28.                     if(x < 0 || y < 0 || x >= len1 || y >= len2 || grid[x][y] == 2) continue;
  29.                     grid[x][y] = 2;
  30.                     temp.push(make_pair(x, y));
  31.                 }
  32.             }
  33.         }
  34.         if(res == 0)return -1;
  35.         return res;
  36.     }
  37. };
复制代码



参考链接:https://leetcode-cn.com/problems ... de-bfs-by-sweetiee/

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-26 12:04

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表