查看: 111| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] 10-08-2026 继续刷题打卡

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
417. Pacific Atlantic Water Flow
一开始写的时候是从每个位置计算是否可以流水到海里,后来ai提醒我说,时间复杂度太高了,因此改为从海边倒流逆向计算哪些位置的水可以流到海里,每个海跑一遍BFS/DFS 就行了。
第一遍写的时候左上角和右下角的位置,重复放入queue里面了,需要注意。
还有就是两个ocean 要处理两遍,visited 和queue 都需要重置,在调用函数的时候把参数设为引用。

class Solution {
int dr[4] = {0, 1, 0, -1};
int dc[4] = {1, 0, -1, 0};
public:
vector> pacificAtlantic(vector>& heights) {
int m = heights.size(), n = heights[0].size();
vector> waterFlow(m, vector(n, 0));
vector> visited(m, vector(n, false));
queue> q;
for (int i = 0; i < m; i++) {
waterFlow[i][0]++;
visited[i][0] = true;
q.push({i, 0});
}
for (int j = 1; j < n; j++) {
waterFlow[0][j]++;
visited[0][j] = true;
q.push({0, j});
}
bfs(heights, waterFlow, visited, q);

visited = vector>(m, vector(n, false));
for (int i = 0; i < m; i++) {
waterFlow[i][n-1]++;
visited[i][n-1] = true;
q.push({i, n-1});
}
for (int j = 0; j < n - 1; j++) {
waterFlow[m-1][j]++;
visited[m-1][j] = true;
q.push({m-1, j});
}
bfs(heights, waterFlow, visited, q);

vector> res;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (waterFlow[i][j] == 2) {
res.push_back({i, j});
}
}
}
return res;
}

void bfs(vector>& heights, vector>& waterFlow, vector>& visited, queue>& q) {
int m = heights.size(), n = heights[0].size();
while(!q.empty()) {
auto [cur_row, cur_col] = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
int nbr_row = cur_row + dr[k];
int nbr_col = cur_col + dc[k];
if (nbr_row < 0 || nbr_col < 0 || nbr_row >= m || nbr_col >= n) continue;
if (visited[nbr_row][nbr_col]) continue;
if (heights[nbr_row][nbr_col] >= heights[cur_row][cur_col]) {
waterFlow[nbr_row][nbr_col]++;
visited[nbr_row][nbr_col] = true;
q.push({nbr_row, nbr_col});
}
}
}
}
};

上一篇:[Solution] OpenAI高频题 GPU Credits — 3 Parts 详解
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

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