1410. 矩阵注水

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/85270348

题目描述:https://www.lintcode.com/problem/matrix-water-injection/description

迷宫类问题,可以用深度优先搜索或广度优先搜索。感觉题解写的都很差,这个题我认为不需要visited数组,因为水的流动决定了它不会走回头路。
这个递归方法已经非常快了。

class Solution {
public:
    string waterInjection(vector<vector<int>> &matrix, int R, int C) {
        if (R==0 || C==0 ||R==matrix.size()-1||C==matrix[0].size()-1) return "YES";
        string up,down,right,left; 
        up=down=right=left="NO";
        if (matrix[R-1][C]<matrix[R][C]) left= waterInjection(matrix,R-1,C);
        if (matrix[R+1][C]<matrix[R][C]) right= waterInjection(matrix,R+1,C);
        if (matrix[R][C+1]<matrix[R][C]) down= waterInjection(matrix,R,C+1);
        if (matrix[R][C-1]<matrix[R][C]) up= waterInjection(matrix,R,C-1);
        if (left=="YES"||right=="YES"||up=="YES"||down=="YES") return "YES";
        else return "NO";
    }
};

非递归,使用队列,也很快:

class Solution {
public:
    string waterInjection(vector<vector<int>> &matrix, int R, int C) {
        if (R==0 || C==0 ||R==matrix.size()-1||C==matrix[0].size()-1) return "YES";
        queue<pair<int,int>> flow;
        flow.push(make_pair(R,C));
        while (!flow.empty())
       {
            pair<int,int> now=flow.front();
            flow.pop();
            if (matrix[now.first-1][now.second]<matrix[now.first][now.second]) 
               if (now.first-1==0 || now.second==0 ||now.first-1==matrix.size()-1||now.second==matrix[0].size()-1) return "YES";
               else flow.push(make_pair(now.first-1,now.second));
            if (matrix[now.first+1][now.second]<matrix[now.first][now.second]) 
               if (now.first+1==0 || now.second==0 ||now.first+1==matrix.size()-1||now.second==matrix[0].size()-1) return "YES";
               else flow.push(make_pair(now.first+1,now.second));
            if (matrix[now.first][now.second-1]<matrix[now.first][now.second]) 
               if (now.first==0 || now.second-1==0 ||now.first==matrix.size()-1||now.second-1==matrix[0].size()-1) return "YES";
               else flow.push(make_pair(now.first,now.second-1));
            if (matrix[now.first][now.second+1]<matrix[now.first][now.second]) 
               if (now.first==0 || now.second+1==0 ||now.first==matrix.size()-1||now.second+1==matrix[0].size()-1) return "YES";
               else flow.push(make_pair(now.first,now.second+1));
       }
       return "NO";
    }
};

猜你喜欢

转载自blog.csdn.net/musechipin/article/details/85270348