Sharing my 28ms C++ solution


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

Log in to reply
 

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