LeetCode1765. 地图中的最高点(BFS)

力扣

 

解题思路:

1.找到水的位置,入队,带出第一层的高度。

2.任意相邻的格子高度差 至多1,通过当前节点带出相邻格子的高度,然后把相邻格子入队;

3.不断地执行此过程直到队列为空; 也就是由点到面铺开计算。

                

代码:



class Solution 
{
public:
   int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
   
    vector<vector<int>> highestPeak(vector<vector<int>> &isWater) 
    {
        int row = isWater.size();
        int col = isWater[0].size();
        vector<vector<int>> ans(row, vector<int>(col, -1)); // -1 表示该格子尚未被访问过
        queue<pair<int, int>> q; //辅助队列

        for (int i = 0; i < row; ++i) 
        {
            for (int j = 0; j < col; ++j) 
            {
                if (isWater[i][j]) 
                {
                    ans[i][j] = 0;
                    q.push(make_pair(i,j)); // 将所有水域入队
                }
            }
        }

        while (!q.empty()) 
        {
           int sz = q.size();
           while(sz--)
           {
				int t_row = q.front().first;
				int t_col = q.front().second;
				q.pop();

				for (int i = 0; i < 4; ++i) //四个方位
				{
					int new_row = t_row + dir[i][0];
					int new_col = t_col + dir[i][1];

					if (new_row < 0 || new_row >= row || new_col < 0 || new_col >= col 
                    ||ans[new_row][new_col] != -1)
					{
						continue; //如果位置越界,访问过,则跳过
					}

                    ans[new_row][new_col] = ans[t_row][t_col] + 1;
                    q.push(make_pair(new_row,new_col));
                }
           }
            
        }

        return ans;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值