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";
    }
}
相关推荐
aichitang202427 分钟前
矩阵详解:从基础概念到实际应用
线性代数·算法·矩阵
雷达学弱狗3 小时前
word操作(持续更新)
矩阵
_Itachi__16 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
不忘不弃16 小时前
计算矩阵A和B的乘积
线性代数·算法·矩阵
不爱写代码的玉子16 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
SY师弟1 天前
51单片机基础部分——矩阵按键检测
嵌入式硬件·矩阵·51单片机
Yxh181377845541 天前
抖去推--短视频矩阵系统源码开发
人工智能·python·矩阵
Psycho_MrZhang1 天前
高等数学基础(矩阵基本操作转置和逆矩阵)
线性代数·矩阵
Bruce_Liuxiaowei2 天前
文件上传漏洞深度解析:检测与绕过技术矩阵
安全·矩阵·文件上传漏洞
天宫风子2 天前
线性代数小述(一)
线性代数·算法·矩阵·抽象代数