LintCode 1410: Matrix Water Injection (BFS题)

本文探讨了一个关于矩阵地形中水流流动的问题,通过BFS算法解决从指定位置开始,水流是否能流向更低处并最终流出矩阵边界。文章提供了一个C++实现的示例,详细解释了如何遍历矩阵并判断水流路径。

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";
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值