463. Island Perimeter

来源:互联网 发布:淘宝开店申请要多久 编辑:程序博客网 时间:2024/06/05 05:20

问题描述: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出现在长方形的四条边上的时候,不会进行超出数组范围的判断操作。

原创粉丝点击