题目:
给一个二维矩阵,每个grid的值代表地势的高度。水流只会沿上下左右流动,且必须从地势高的地方流向地势低的地方。视为矩阵四面环水,现在从(R,C)处注水,问水能否流到矩阵外面去?
样例:
1.给出
mat =
[
[10,18,13],
[9,8,7],
[1,2,3]
]
R = 1, C = 1, 返回 “YES”。
解释:
(1,1) →(1,2)→流出。
2.给出
mat =
[
[10,18,13],
[9,7,8],
[1,11,3]
]
R = 1, C = 1, 返回 “NO”。
解释:
从(1,1)无法流向任何其他格点,故无法流出去。
思路:
这是一题迷宫类问题,可以用回溯的方法来解题,只要水能从matrix[R][C]流向矩阵的最外围,那么就返回YES。水只能由高往低流走,如果matrix[R][C] < matrix[A][B],那么水无法流向(A,B)这个位置。
答案:
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
*/
private String res = "NO";
public String waterInjection(int[][] matrix, int R, int C) {
// Write your code here
if(R == 0||C == 0||R == matrix.length-1||C == matrix.length-1){
return "YES";
}
check(matrix,R,C);
return res;
}
public void check(int[][] matrix, int R, int C){
if(R == 0||C == 0||R == matrix.length-1||C == matrix[0].length-1){
res = "YES";
return;
}
if(canflow(matrix,R,C,R-1,C)){//up
check(matrix,R-1,C);
}
if(canflow(matrix,R,C,R,C-1)){//left
check(matrix,R,C-1);
}
if(canflow(matrix,R,C,R+1,C)){//down
check(matrix,R+1,C);
}
if(canflow(matrix,R,C,R,C+1)){//right
check(matrix,R,C+1);
}
}
public static boolean canflow(int[][] matrix,int R,int C,int targetR,int targetC){
if(matrix[R][C]<=matrix[targetR][targetC]){
return false;
}
return true;
}
}