C++99ms,how to improve the algorithm


  • 0
    O

    class Solution {
    public:
    int islandPerimeter(vector<vector<int>>& grid) {
    int r = grid[0].size();
    int l = grid.size();
    int ret = 0;
    for(int i = 0;i < l;i++)
    {
    for(int j = 0;j< r;j++)
    {
    ret += getLine(i,j,grid);
    }
    }
    return ret;
    }
    private:
    int getLine(int i,int j,vector<vector<int>>& grid)
    {
    int ret = 0;
    if(grid[i][j] ==0 )
    return ret;
    if(i== 0 || grid[i-1][j] == 0)
    ret++;
    if(i == grid.size()-1 || grid[i+1][j] == 0)
    ret++;
    if(j == 0|| grid[i][j - 1] == 0)
    ret++;
    if(j == grid[0].size()-1 || grid[i][j + 1] == 0 )
    ret++;
    return ret;
    }
    };


Log in to reply
 

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