1410. Matrix Water Injection
Given a two-dimensional matrix, the value of each grid represents the height of the terrain. The flow of water will only flow up, down, right and left, and it must flow from the high ground to the low ground. As the matrix is surrounded by water, it is now filled with water from (R,C) and asked if water can flow out of the matrix.
Example
Example1
Input:
mat =
[
[10,18,13],
[9,8,7],
[1,2,3]
] and R = 1, C = 1
Output: "YES"
Explanation:
(1,1) →(1,2)→Outflow.
Example2
Input:
mat =
[
[10,18,13],
[9,7,8],
[1,11,3]
] and R = 1, C = 1
Output: "NO"
Explanation:
Since (1,1) cannot flow to any other grid, it cannot flow out.
Notice
The input matrix size is n x n, n <= 200.
Ensure that each height is a positive integer.
解法1: BFS。
class Solution {
public:
/**
* @param matrix: the height matrix
* @param R: the row of (R,C)
* @param C: the columns of (R,C)
* @return: Whether the water can flow outside
*/
string waterInjection(vector<vector<int>> &matrix, int R, int C) {
int nRow = matrix.size();
if (nRow == 0) return "NO";
int nCol = matrix[0].size();
queue<pair<int,int>> q;
vector<int> dx = {0, 0, 1, -1};
vector<int> dy = {1, -1, 0, 0};
q.push({R, C});
while(!q.empty()) {
pair<int, int> frontNode = q.front();
q.pop();
if (frontNode.first == nRow - 1 || frontNode.second == nCol - 1) return "YES";
for (int i = 0; i < 4; ++i) {
int newX = frontNode.first + dx[i];
int newY = frontNode.second + dy[i];
if (newX >= 0 && newX < nRow && newY >= 0 && newY < nCol) {
if (matrix[newX][newY] < matrix[frontNode.first][frontNode.second]) {
q.push({newX, newY});
}
}
}
}
return "NO";
}
};
本文探讨了一个关于矩阵地形中水流流动的问题,通过BFS算法解决从指定位置开始,水流是否能流向更低处并最终流出矩阵边界。文章提供了一个C++实现的示例,详细解释了如何遍历矩阵并判断水流路径。

被折叠的 条评论
为什么被折叠?



