C++ O(MN) solution


  • 0
    M
        size_t width = grid[0].size();
        size_t height = grid.size();
        int i, j;
        
        int** sum_array = new int* [height];
        for (i = 0; i < height; ++i) {
            sum_array[i] = new int[width];
        }
        
        for(i = 0; i < height; ++ i){
            for(j = 0; j < width; ++ j){
                sum_array[i][j] = 0;
                if(grid[i][j] != 0){
                    sum_array[i][j] = 4;
                    if(j > 0 && grid[i][j - 1] != 0){
                        sum_array[i][j] --;
                    }
                    if(j < width - 1 && grid[i][j + 1] != 0){
                        sum_array[i][j] --;
                    }
                    if(i > 0 && grid[i - 1][j] != 0){
                        sum_array[i][j] --;
                    }
                    if(i < height - 1 && grid[i + 1][j] != 0){
                        sum_array[i][j] --;
                    }
                }
            }
        }
        
        int sum = 0;
        for(i = 0; i < height; ++ i){
            for(j = 0; j < width; ++ j){
                sum += sum_array[i][j];
            }
        }
        
        return sum;
    

Log in to reply
 

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