Anyone who knew Python well could help to find the problem? (I passed with the same algor in C++ )


  • 0

    Hey I am new to Python.

    I guess the reason my below Python solution wrong is something Python unique character I don't understand. (Since I used the exactly same algorithm written in C++ and it is done well.)

    The idea is just dfs, which is very simple. I first paste my C++ solution, which has passed the OJ. The following is exactly the same, but in Python, and it is wrong.

    Any advice is appreciated !!

    // C++ for DFS
    class Solution {
    public:
        int minArea(vector<vector<char>>& image, int x, int y) {
            int left = y, right = y, up = x, down = x;
            dfs(image, x, y, left, right, up, down);
            return (right - left + 1) * (down - up + 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(left, y); 
            right = max(right, y);
            up = min(up, x);
            down = max(down, x);
            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);
        }
    };
    
    # python in dfs
    class Solution(object):
        def minArea(self, image, x, y):
            if image is None or len(image) == 0:
                return 0
    
            left, right = y, y
            up, down = x, x
    
            self.dfs(image, x, y, left, right, up, down)
    
            return (right - left + 1) * (down - up + 1)
    
    
        def dfs(self , image, x, y, left, right, up, down):
            if x< 0 or x >= len(image) or y < 0 or y >= len(image[0]) or image[x][y] != '1':
                return
    
            left = min(left, y)
            right = max(y, right)
            up = min(up, x)
            down = max (down, x)
    
            image[x] = image[x][:y] + 'm' + image[x][y+1:]
    
            self.dfs(image, x + 1, y, left, right, up, down) # down
            self.dfs(image, x - 1, y, left, right, up, down) # up
            self.dfs(image, x, y + 1, left, right, up, down) # right
            self.dfs(image, x, y - 1, left, right, up, down) # left
    
    

Log in to reply
 

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