A simple C solution


  • 0
    C

    If a land grid has 0 neighboring land grid, its perimeter is 4
    If a land grid has 4 neighboring land grids, its perimeter is 0
    the perimeter decreases by 1 for every neighboring land grid.

    int islandPerimeter(int** grid, int gridRowSize, int gridColSize) {
        int numofneighbor = 0;
        int perimeter = 0;
        int i,j;
        
        for (i=0; i< gridRowSize; i++) {
            for (j=0; j<gridColSize; j++) {
                if(*(*(grid+i)+j)) {
                    // this is a land
                    if (i-1>=0 && *(*(grid+i-1)+j)) {
                        numofneighbor ++;
                    }
                    if (i+1<gridRowSize && *(*(grid+i+1)+j)) {
                        numofneighbor++;
                    }
                    if (j-1>=0 && *(*(grid+i)+j-1)) {
                        numofneighbor++;
                    } 
                    if (j+1< gridColSize && *(*(grid+i)+j+1)) {
                        numofneighbor++;
                    }
                    perimeter = perimeter + (4- numofneighbor);
                    numofneighbor = 0;
                }
                
            }
        }
        return perimeter;
    }
    

Log in to reply
 

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