463. Island Perimeter

问题描述:You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.
解题思路:将计算周长转换为计算0-1键的个数,以及1在长方形四个边上的情况。首先找出二维数组中出现1的位置,接着判断上下左右四个方向0的个数,注意要考虑在四条边以及四个角的情况。

class Solution {
    public int islandPerimeter(int[][] grid) {
        int length = grid[0].length;
        int width = grid.length;
        int result = 0;
        for(int i = 0;i < width;++i ){
            for(int j = 0;j < length;++j ){
                if(grid[i][j] == 1){ 
                     if(j==0) result++;
                     if(j==length-1) result++;
                     if(i==0) result++;
                     if(i==width-1) result++;
                     if(j > 0 && grid[i][j-1]==0) result++;
                     if(j < length-1 && grid[i][j+1]==0) result++;                     
                     if(i > 0 && grid[i-1][j]==0) result++;
                     if(i < width-1 && grid[i+1][j]==0) result++;
                    }
             }
        }
        return result;

    }

}

运行时间为127 ms。先用四个判断,保证了目标位置出现在四条边、四个角、二维数组只有一个数的情况;代码中利用了&&操作的短路性质,保证了当1出现在长方形的四条边上的时候,不会进行超出数组范围的判断操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值