Leetcode 463. Island Perimeter

来源:互联网 发布:总裁高级研修班知乎 编辑:程序博客网 时间:2024/05/16 00:33

For details. 

/** * perimeter = 4*island - 2*neighbor */ public class Solution {    public int islandPerimeter(int[][] grid) {        int island = 0, neighbor = 0;        for (int i=0; i<grid.length; i++)            for (int j=0; j<grid[0].length; j++) {                if (grid[i][j] == 1) {                    island++;                    // search right and down if there are neighbors                    // the reason for searching right and down is                     // we iterate from left and top                    if (i < grid.length-1 && grid[i+1][j] == 1) neighbor++;                    if (j < grid[0].length-1 && grid[i][j+1] == 1) neighbor++;                }            }        return 4*island - 2*neighbor;    }}


0 0
原创粉丝点击