lintcode 1410 · 矩阵注水【BFS 中等 vip】

题目链接,描述

https://www.lintcode.com/problem/1410

java 复制代码
给一个二维矩阵,每个grid的值代表地势的高度。水流只会沿上下左右流动,且必须从地势高的地方流向地势低的地方。视为矩阵四面环水,现在从(R,C)处注水,问水能否流到矩阵外面去?



输入的矩阵大小为n x n ,n <= 200。
保证每个高度均为正整数。
样例
样例1

输入: 
mat =
[
    [10,18,13],
    [9,8,7],
    [1,2,3]
] and R = 1, C = 1
输出: "YES"
解释: 
(1,1) → (1,2)→ 流出。
样例2

输入: 
mat = 
[
    [10,18,13],
    [9,7,8],
    [1,11,3]
] and R = 1, C = 1
输出: "NO"
解释: 
从(1,1)无法流向任何其他格点,故无法流出去。

思路

前置知识:BFS,Queue

参考代码

java 复制代码
public class Solution {
    /**
     * @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
     */
    public String waterInjection(int[][] matrix, int r, int c) {
        //BFS
        int n = matrix.length,m=matrix[0].length;
        Queue<int[]> queue = new LinkedList<>();

        queue.add(new int[]{r,c});
        int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
        while (!queue.isEmpty()){
            int[] poll = queue.poll();
            int x = poll[0],y=poll[1];

            if(x ==0 || x ==n-1 || y ==0 || y==m-1)
                return "YES";

            for (int[] dir : dirs) {
                int x1 = x+dir[0],y1=y+dir[1];
                if(x1>=0 && x1<n && y1>=0 && y1<m && matrix[x][y] > matrix[x1][y1]){
                    queue.add(new int[]{x1,y1});
                }
            }
        }
        return "NO";
    }
}
相关推荐
Regulus-Moon1 天前
人工智能数学基础:矩阵特征分解与压缩实战
人工智能·线性代数·矩阵
JianZhen✓10 天前
电商 SKU 选择器:后端只给扁平列表,前端怎么反推规格矩阵并做到 O(1) 命中
前端·矩阵·状态模式
tellmewhoisi12 天前
深度学习0:数学知识:(雅可比矩阵)
人工智能·深度学习·矩阵
lisw0518 天前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
DFT计算杂谈19 天前
可DIY布里渊区图像绘制编辑器
人工智能·机器学习·语言模型·矩阵·编辑器
Pniubi19 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
Pniubi20 天前
力扣73 矩阵置零
算法·leetcode·矩阵
kingx321 天前
Bugku 逆向 MatrixHunter:黑盒 oracle + GF(2) 消元出唯一解
网络安全·矩阵·逆向·ctf
吴名氏.24 天前
Java转AI Agent教程(第九周)错误矩阵
java·人工智能·矩阵·ai agent