Sharing my 166ms C++ solution


  • 2
    T
    class Solution {
    private:
        void wallsAndGatesHelper(vector<vector<int>>& rooms, int i, int j, int depth)
        {
            int m = rooms.size();
            int n = rooms[0].size();
            if(i<0 || i>=m || j<0 || j>=n)
                return;
            else if(rooms[i][j]<=depth)
                return;
            else
            {
                rooms[i][j]=depth;
                wallsAndGatesHelper(rooms, i-1, j, depth+1);
                wallsAndGatesHelper(rooms, i+1, j, depth+1);
                wallsAndGatesHelper(rooms, i, j-1, depth+1);
                wallsAndGatesHelper(rooms, i, j+1, depth+1);
            }
        }
        
    public:
        void wallsAndGates(vector<vector<int>>& rooms) {
            int m = rooms.size();
            if(m==0)
                return;
            int n = rooms[0].size();
            if(n==0)
                return;
                
            int i, j;
            for(i=0; i<m; i++)
                for(j=0; j<n; j++)
                    if(rooms[i][j]==0)
                    {
                        wallsAndGatesHelper(rooms, i-1, j, 1);
                        wallsAndGatesHelper(rooms, i+1, j, 1);
                        wallsAndGatesHelper(rooms, i, j-1, 1);
                        wallsAndGatesHelper(rooms, i, j+1, 1);
                    }
                    
        }
    };

Log in to reply
 

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