C++ - Easy to Understand (Find edges)


  • 3
        int n = grid.size(); //num_rows
        int m = grid[0].size(); //num_cols
        int sum = 0,i,j;
        for(i=0;i<n;i++)
        {
            for(j=0;j<m-1;j++)
            {
                sum += abs(grid[i][j+1]-grid[i][j]); //find vertical edges
            }
            sum = sum+grid[i][j]+grid[i][0]; //account for 2 corner blocks
        }
        
        for(j=0;j<m;j++)
        {
            for(i=0;i<n-1;i++)
            {
                sum += abs(grid[i+1][j]-grid[i][j]); //find horizontal edges
            }
            sum = sum + grid[i][j] + grid[0][j]; //account for 2 corner blocks
        }
        return sum;

  • 0
    G

    Your runtime ?
    Mine is

            int ans=0;
            int nc=grid[0].size(),nr=grid.size();
            
            for(int i=0;i<nr;i++)
                for(int j=0;j<nc;j++)
                {
                    if(grid[i][j]==1)
                    {
                        ans+=4;
                        if(i-1>=0)
                            ans-=grid[i-1][j];
                        if(j+1<=nc-1)
                            ans-=grid[i][j+1];
                        if(i+1<=nr-1)
                            ans-=grid[i+1][j];
                        if(j-1>=0)
                            ans-=grid[i][j-1];
                    }
             }
            return ans;
        }
    

    It's runtime is 129ms could you suggest some ways to reduce it.


Log in to reply
 

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