<Island Perimeter> returned different values when it ran and submitted


  • 0
    C

    Hi everyone, I have met something really strange with the "Island Perimeter" problem.

    If the parameter vector<vector<int>> contains [[1,1,1]], the answer should be 8, and when I pressed the Run button, it returned 8 which was correct, but when I submited it, it returned 6. And I tried the code in my own computer with g++ 4.9.3, it proved that the return value was exactly 8. Is there somebody who can figure this out for me? Thank you!

    BTW, I can't find the problem "Island Perimeter" in the OJ topic...

    And here is my code:

    class Solution {
    public:
        int islandPerimeter(vector <vector<int> >& grid) {
            int height = grid.size();
            int width = grid[0].size();
            if (height == 0 || width == 0)  return 0;
            int *p = new int[width];    //array p stands for the condition of last column
            memset(p,0,width);
            int sum_cells = 0;
            int overlap_lines = 0;
            for(int i = 0; i < height; i++){
                for(int j = 0; j < width; j++){
                    if (grid[i][j] == 1){
                        sum_cells++;
                        if (p[j] == 1){    //check the last column
                            overlap_lines++;
                        }
                        if (((j - 1) >= 0) && (p[j - 1] == 1)){    //if there are adjacent cells
                            overlap_lines++;
                        }
                        p[j] = 1;
                    }else{
                        p[j] = 0;
                    }
                }
            }
            return sum_cells * 4 - overlap_lines * 2;
        }
    };
    

Log in to reply
 

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