Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

463. Island Perimeter #157

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public int islandPerimeter(int[][] grid) { int isIsland = 0, isCount = 0;

    for(int i = 0; i < grid.length; i++) {
        for(int j = 0; j <grid[i].length; j++) {
            if(grid[i][j] == 1) {
                isIsland++; //count the number of island
                if(i < grid.length - 1 && grid[i+1][j] == 1) isCount++; // count down neighbours
                if(j < grid[i].length - 1 && grid[i][j+1] == 1) isCount++; // count right neighbours
            }
        }
    }
    return 4*isIsland - 2*isCount;
}

} / loop over the matrix and count the number of islands; if the current dot is an island, count if it has any right neighbour or down neighbour; the result is islands 4 - neighbours 2 /

Shawngbk commented 7 years ago

google