当前位置:网站首页>417.太平洋大西洋水流问题
417.太平洋大西洋水流问题
2022-07-30 05:38:00 【Linke66】

解题思路:
一开始自己的思路是看每一个点是否能流到太平洋和大西洋,很复杂,各种细节考虑不到。看了题解觉得这个方法很好,记录一下。
我们从四个边开始往高处走,能走到的位置就是能流到对应边旁边的洋流。
can_reach_p,(太平洋 pacific)代表能到达太平洋;
can_reach_a,(大西洋 atlantic)代表能到达大西洋。
假如某个点的can_reach_p和can_reach_a都为true,说明符合条件。
具体思路看代码。
class Solution {
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
if(heights.empty()||heights[0].empty()) return {
};
int m=heights.size(),n=heights[0].size();
vector<vector<int>>ret;
vector<vector<bool>> can_reach_p(m,vector<bool>(n,false)); //能到达太平洋 pacific ocean
vector<vector<bool>> can_reach_a=can_reach_p; //能到达大西洋
for(int i=0;i<m;++i){
dfs(heights,can_reach_p,i,0);
dfs(heights,can_reach_a,i,n-1);
}
for(int i=0;i<n;++i){
dfs(heights,can_reach_p,0,i);
dfs(heights,can_reach_a,m-1,i);
}
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
if(can_reach_a[i][j]&&can_reach_p[i][j]){
ret.push_back({
i,j});
}
}
}
return ret;
}
void dfs(const vector<vector<int>>& heights,
vector<vector<bool>> &can_reach,
int x,int y)
{
if(can_reach[x][y]==true) return;
can_reach[x][y]=true;
if(x-1>=0&&heights[x-1][y]>=heights[x][y])
dfs(heights,can_reach,x-1,y);
if(y-1>=0&&heights[x][y-1]>=heights[x][y])
dfs(heights,can_reach,x,y-1);
if(x+1<heights.size()&&heights[x+1][y]>=heights[x][y])
dfs(heights,can_reach,x+1,y);
if(y+1<heights[0].size()&&heights[x][y+1]>=heights[x][y])
dfs(heights,can_reach,x,y+1);
}
};
边栏推荐
猜你喜欢

mysql 中 in 的用法

Error: listen EADDRINUSE: address already in use 127.0.0.1:3000

Navicat cannot connect to mysql super detailed processing method

Navicat new database

cookie和session区别

Anaconda安装教程

2022 SQL big factory high-frequency practical interview questions (detailed analysis)

使用DataEase开源工具制作一个高质量的数据大屏

St. Regis Takeaway Project: New dishes and dishes paged query

flask的笔记
随机推荐
Thymeleaf简介
mysql time field is set to current time by default
[Koltin Flow (2)] The end operator of the Flow operator
“tensorflow.keras.preprocessing“ has no attribute “image_dataset_from_directory“
Navicat connection MySQL error: 1045 - Access denied for user 'root'@'localhost' (using password YES)
使用DataEase开源工具制作一个高质量的数据大屏
131.分割回文串
flask-socketio实现的网页聊天室(二)
pytorch中的线性代数
839. 模拟堆
pwn-ROP
Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution
[详解C语言]一文带你玩转数组
Numpy 中 np.vstack() 和 np.hstack() 简单解析
839. Simulated heap
MySQL模糊查询性能优化
4461. 范围分区(Google Kickstart2022 Round C Problem B)
MySQL Soul 16 Questions, how many questions can you last?
每日练习------输出一个整数的二进制数、八进制数、十六进制数。
Falling ants (Peking University entrance exam questions)