Intuitive C Solution


  • 0
    N
    1. Iterate through the grid.
    2. Whenever you get a land [1], check all the neighbours.
    3. If neighbour is out of bound or contains water[0], just increment the count.
    int islandPerimeter(int** grid, int row, int col) {
        int xy[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
        int count = 0;
    
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(grid[i][j] == 1){
                  for(int k = 0; k < 4; k++){
                     //Check for out of bound neighbours
                     if(i+xy[k][0] < 0 || i+xy[k][0] >= row || j+xy[k][1] < 0 || j+xy[k][1] >= col)
                        count++;
                     //Check for water
                     else if(grid[i+xy[k][0]][j+xy[k][1]] == 0)
                         count++;                          
                  }               
                }
            }
        }
        return count;
    }
    
    

Log in to reply
 

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