Why can't pass all test cases?


  • 0
    A

    please help me to improve the code to pass all the test cases! thankyou very much!

    here is my code:

    class Solution {
    public:
    int numIslands(vector<vector<char>>& grid) {
    int h=grid.size();
    if(h<1)
    return 0;
    int l=grid[0].size();
    if(l<1)
    return 0;

    	int count=0;
    	while(1)
    	{
    		int i,j;
    		for(i=0;i<h;i++)
    			for(j=0;j<l;j++)
    				if(grid[i][j]=='1')
    				{
    					count++;
    					bt(grid,i,j);
    					break;
    				}
    					//if((i==0||grid[i-1][j]=='0')&&(j==0||grid[i][j-1]=='0'))
    					//	count++;		// a new island
    		if(i==h&&j==l)
    			return count;
    	}
    		
    }
    
    void bt(vector<vector<char>>& grid,int i,int j)
    {
    	grid[i][j]='0';
    
    	if(i>0&&grid[i-1][j]=='1')
    		bt(grid,i-1,j);
    	if(j>0&&grid[i][j-1]=='1')
    		bt(grid,i,j-1);
    	if(i<grid.size()-1&&grid[i+1][j]=='1')
    		bt(grid,i+1,j);
    	if(j<grid[i].size()-1&&grid[i][j+1]=='1')
    		bt(grid,i,j+1);
    }
    

    };


Log in to reply
 

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