417.太平洋大西洋水流问题
说明:本人这个属于暴力dfs方法,效率不高, 但是dfs这个方法比较好理解
思想:
- 建立已访问矩阵v和能够到达矩阵visited
- visited每个元素有两个值,第一值visited[i][j][0]表示(i,j)能够达到太平洋,第二值visited[i][j][1]表示(i,j)能够达到大西洋
- 进行dfs搜索
//417.
typedef vector<vector<int>> MATRIX;
typedef vector<vector<vector<bool>>> VISITED;
void DFS417(const MATRIX& matrix, VISITED& visited, MATRIX& v, int x, int y) {
if (x == 0 || y == 0 || x ==matrix.size()|| y ==matrix[0].size() || v[x][y] == 1)
return;
v[x][y] = 1;
vector<int> dx{ 0,0,1,-1 };
vector<int> dy{ 1,-1,0,0 };
for (int i = 0; i < 4; ++i) {
int nx = x + dx[i], ny = y + dy[i];
if (matrix[x][y] < matrix[nx][ny])
continue;
auto& temp = visited[nx][ny];
visited[x][y][0] = visited[x][y][0] || temp[0];
visited[x][y][1] = visited[x][y][1] || temp[1];
if (visited[x][y][0] && visited[x][y][1])
break;
DFS417(matrix, visited, v, nx, ny);
temp = visited[nx][ny];
visited[x][y][0] = visited[x][y][0] || temp[0];
visited[x][y][1] = visited[x][y][1] || temp[1];
if (visited[x][y][0] && visited[x][y][1])
break;
}
v[x][y] = 0;
}
MATRIX pacificAtlantic(MATRIX& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0)
return{};
const int n = matrix.size(), m = matrix[0].size();
MATRIX v(n+2, vector<int>(m+2, 0));
VISITED visited(n+2, vector<vector<bool>>(m+2, vector<bool>{false, false}));
MATRIX M(n + 2, vector<int>(m + 2, 0));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
M[i + 1][j + 1] = matrix[i][j];
for (int y = 0; y < m+2; ++y) {
v[0][y] = 1; visited[0][y][0] = true;
v[n+1][y] = 1; visited[n+1][y][1] = true;
}
for (int x = 0; x < n+2; ++x) {
v[x][0] = 1; visited[x][0][0] = true;
v[x][m+1] = 1; visited[x][m+1][1] = true;
}
MATRIX re;
for (int i = 1; i < n+2; ++i)
for (int j = 1; j < m+2; ++j) {
if (v[i][j] == 0 ||(visited[i][j][0] || visited[i][j][1])) {
DFS417(M, visited, v, i, j);
v[i][j] = 1;
}
if (visited[i][j][0] && visited[i][j][1])
re.push_back({ i-1,j-1 });
}
return re;
}