LintCode 题解 |Microsoft 面试题:Matrix Water Injection

题目描述

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

思路点拨

从(R,C)开始DFS,看是否能碰到边界。返回YES或者NO。

考点分析

简单的热身搜索,一定要做到bugfree,注意水是从高处向低处流动

九章参考程序

http://www.jiuzhang.com/solution/matrix-water-injection/?utm_source=csdn

/**
* 本参考程序来自九章算法,由 @林助教 提供。版权所有,转发请注明出处。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
* - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
* - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
*/ 

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
     */
    class Pair {
        public int x;
        public int y;
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
    } 
    
    int dir[][] = {{1,0},{-1,0},{0,1},{0,-1}};
    
    public String waterInjection(int[][] matrix, int R, int C) {
        // Write your code here
        int[][] vis = new int[matrix.length][matrix[0].length];
        Queue<Pair> q = new LinkedList<Pair>();
        q.offer(new Pair(R, C));
        vis[R][C]=1;
        while(!q.isEmpty()) {
            Pair x = q.poll();
            if(x.x == 0 || x.x == matrix.length - 1 || x.y == 0 || x.y == matrix[0].length - 1) {
                return "YES";
            }
            int num = matrix[x.x][x.y];
            for(int i = 0; i < 4; i++) {
                int tx = x.x + dir[i][0];
                int ty = x.y + dir[i][1];
                if(tx < 0 || tx >= matrix.length || ty < 0 || ty >= matrix[0].length) {
                    continue;
                }
                if(matrix[tx][ty] < num && vis[tx][ty] == 0) {
                    q.offer(new Pair(tx,ty));
                    vis[tx][ty] = 1;
                }
            }
        }
        return "NO";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值