C++ DFS solution


  • 0
    U
    class Solution {
    public:
        int minArea(vector<vector<char>>& image, int x, int y) {
            int left = x, right = x, up = y, down = y;
            dfs(image, x, y, left, right, up, down);
            return (right-left+1)*(up-down+1);
        }
        void dfs(vector<vector<char>>& image, int x, int y, int& left, int& right, int& up, int& down){
            if (x<0 || x>=image.size() || y<0|| y>=image[0].size() || image[x][y] != '1')
                return;
            left = min(x, left);
            right = max(x, right);
            up = max(y, up);
            down = min(y, down);
            image[x][y] = '2';
            dfs(image, x+1, y, left, right, up, down);
            dfs(image, x-1, y, left, right, up, down);
            dfs(image, x, y+1, left, right, up, down);
            dfs(image, x, y-1, left, right, up, down);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.