Help with my logic?


  • 0
    A

    Re: [Java/C++] Clean Code

    Hi, this is my first time posting here! Can someone please help me understand why my logic did not work for one of the test cases that expected result as 32 but mine produced 31? I thought my logic was almost same as above. I am using vector<char> instead of int to store the movements.

    class Solution {
    private:
    bool checkboundary(vector<vector<int>>& grid,int i, int j)
    {
    return (i >=0 && i<grid.size() && j>=0 && j<grid[0].size());
    }
    public:
    void recurse(int i, int j,vector<vector<int>> &grid, std::vector<char>& vec)
    {
    grid[i][j] = -1;

        if (checkboundary(grid, i-1, j) && grid[i-1][j]==1)
        {
            vec.push_back('U');
            recurse(i-1,j, grid, vec);
        }
        if (checkboundary(grid, i+1, j) && grid[i+1][j]==1)
        {
            vec.push_back('D');
            recurse(i+1,j, grid, vec);
        }
        
        if (checkboundary(grid, i, j-1) && grid[i][j-1]==1)
        {
            vec.push_back('L');
            recurse(i,j-1, grid, vec);
        }
        if (checkboundary(grid, i, j+1) && grid[i][j+1]==1)
        {
            vec.push_back('R');
            recurse(i,j+1, grid, vec);
        }
        
    }
    
    int numDistinctIslands(vector<vector<int>>& grid) {
    int M = grid.size();
        int N = grid[0].size();
        
        std::set<std::vector<char>>mset;
        for (int i=0;i<M;i++)
        {
            for(int j=0;j<N;j++)
            {
                if (grid[i][j]==1)
                {
                    std::vector<char> vec;
                    vec.push_back('C');
                    recurse(i,j, grid, vec);
                    
                    mset.insert(vec);                   
                    
                }
            }
        }
        
        return mset.size();
        
    }
    

    };


Log in to reply
 

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