当前位置:网站首页>leetcode417. Pacific Atlantic current problems (medium)

leetcode417. Pacific Atlantic current problems (medium)

2022-06-11 16:15:00 Heavy garbage

 Insert picture description here
 Insert picture description here
 Insert picture description here
Ideas : Two dimensional coordinates dfs
Train of thought details : If the element is searched , The complexity will be very high , Think backwards , That is, water flows upward . Search from the left and from the top , Go to == perhaps > Search your location , The place that can be reached is the square that can flow to the Pacific Ocean , The same goes for the Atlantic Ocean , The square that can be reached is ans.

class Solution {
    
public:
    vector<vector<int>> ans;
    int flag[205][205];
    int xy[4][2] = {
    0, 1, 0, -1, 1, 0, -1, 0};
    void dfs(vector<vector<int>>& heights, int x, int y, int val) {
    

        int n = heights.size(), m = heights[0].size();
        flag[x][y] = val;
        for (int i = 0; i < 4; ++i) {
    
            int xx = x + xy[i][0];
            int yy = y + xy[i][1];
            if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
            if (heights[xx][yy] < heights[x][y]) continue;
            if (!flag[xx][yy]) dfs(heights, xx, yy, val);
            if (val == 2 && flag[xx][yy] == 1) {
    
                ans.push_back({
    xx, yy});
                dfs(heights, xx, yy, val);
            }
        }
    }
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
    
 
        int n = heights.size(), m = heights[0].size();
        for (int i = 0; i < n; ++i) dfs(heights, i, 0, 1);
        for (int j = 0; j < m; ++j) dfs(heights, 0, j, 1);
        for (int i = 0; i < n; ++i) {
    
            if (flag[i][m - 1] == 1) ans.push_back({
    i, m - 1}); //
            dfs(heights, i, m - 1, 2);
        }
        for (int j = 0; j < m; ++j) {
    
            if (flag[n - 1][j] == 1) ans.push_back({
    n - 1, j});
            dfs(heights, n - 1, j, 2);
        }
        return ans;
    }
};

It's easy to get wrong : The start of the search , It could be ans, To call dfs Special consideration before .

原网站

版权声明
本文为[Heavy garbage]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111601470545.html

随机推荐