本题链接: 水流问题
本题一开始的想法是遍历每个点,然后看这个点 能不能同时到达第一组边界和第二组边界,但是超时了。然后学习了 代码随想录 中该题的解法:
- 从第一组边界上的节点 逆流而上,将遍历过的节点都标记上。
- 同样从第二组边界的边上节点 逆流而上,将遍历过的节点也标记上。
- 那么同时被标记的节点,就是能同时到达第一边界和第二边界的节点
- 以下给出了使用dfs和bfs搜索的代码
#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
void dfs(vector<vector<int>>& graph, vector<vector<bool>>& visited, int x, int y){
for(int i = 0; i < 4; i++){
int nextx = x + dir[i][0];
int nexty = y + dir[i][1];
if(nextx < 0 || nextx >= graph.size() || nexty < 0 || nexty >= graph[0].size()){
continue;
}
if(graph[nextx][nexty] >= graph[x][y] && !visited[nextx][nexty]){
visited[nextx][nexty] = true;
dfs(graph, visited, nextx, nexty);
}
}
}
void bfs(vector<vector<int>>& graph, vector<vector<bool>>& visited, int x, int y){
queue<pair<int, int>> que;
que.push({x, y});
while(!que.empty()){
pair<int, int> cur = que.front();
que.pop();
for(int i = 0; i < 4; i++){
int nextx = cur.first + dir[i][0];
int nexty = cur.second + dir[i][1];
if(nextx < 0 || nextx >= graph.size() || nexty < 0 || nexty >= graph[0].size()){
continue;
}
if(graph[nextx][nexty] >= graph[cur.first][cur.second] && !visited[nextx][nexty]){
visited[nextx][nexty] = true;
que.push({nextx, nexty});
}
}
}
}
int main(){
int n,m;
cin >> n >> m;
vector<vector<int>> graph(n, vector<int>(m));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> graph[i][j];
}
}
vector<vector<bool>> firstVisited(n, vector<bool>(m, false));
vector<vector<bool>> secondVisited(n, vector<bool>(m, false));
for(int i = 0; i < n; i++){
if(!firstVisited[i][0]){
firstVisited[i][0] = true;
// dfs(graph, firstVisited, i, 0);
bfs(graph, firstVisited, i, 0);
}
if(!secondVisited[i][m - 1]){
secondVisited[i][m - 1] = true;
// dfs(graph, secondVisited, i, m - 1);
bfs(graph, secondVisited, i, m - 1);
}
}
for(int j = 0; j < m; j++){
if(!firstVisited[0][j]){
firstVisited[0][j] = true;
// dfs(graph, firstVisited, 0, j);
bfs(graph, firstVisited, 0, j);
}
if(!secondVisited[n - 1][j]){
secondVisited[n - 1][j] = true;
// dfs(graph, secondVisited, n - 1, j);
bfs(graph, secondVisited, n - 1, j);
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(firstVisited[i][j] == 1 && secondVisited[i][j] == 1){
cout << i << ' ' << j << endl;
}
}
}
return 0;
}