463. Island Perimeter

来源:互联网 发布:方舟生存进化淘宝购买 编辑:程序博客网 时间:2024/05/29 08:04

Total Accepted: 27942
Total Submissions: 49580
Difficulty: Easy
Contributors: amankaraj
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.

Example:

[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]

Answer: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
这道题给了我们一个格子图,若干连在一起的格子形成了一个小岛,规定了图中只有一个相连的岛,且岛中没有湖,让我们求岛的周长。我们知道一个格子有四条边,但是当两个格子相邻,周围为6,若某个格子四周都有格子,那么这个格子的四个边都不算周长。那么我们怎么统计出岛的周长呢?第一种方法,我们对于每个格子的四条边分别来处理,首先看左边的边,只有当左边的边处于第一个位置或者当前格子的左面没有岛格子的时候,左边的边计入周长。其他三条边的分析情况都跟左边的边相似,这里就不多叙述了,参见代码如下:

解法1:

        class Solution {public:    int islandPerimeter(vector<vector<int>>& grid) {        if (grid.empty() || grid[0].empty()) return 0;        int m = grid.size(), n = grid[0].size(), res = 0;//m为行,n为列        for (int i = 0; i < m; ++i) {            for (int j = 0; j < n; ++j) {//例如第一行的第二列的1,同时满足3种情况,+3                if (grid[i][j] == 0) continue;//这句话的作用是使下面的都满足等于1的情况                if (j == 0 || grid[i][j - 1] == 0) ++res;//处于第一列或者其左边等于0                if (i == 0 || grid[i - 1][j] == 0) ++res;//处于第一行或者其上面等于0                if (j == n - 1 || grid[i][j + 1] == 0) ++res;//处于最后一列或者其右边等于0                if (i == m - 1 || grid[i + 1][j] == 0) ++res;//处于最后一行或者其下面等于0            }        }        return res;    }};

解法2:下面这种方法对于每个岛屿格子先默认加上四条边,然后检查其左面和上面是否有岛屿格子,有的话分别减去两条边:(为什么是上面和左面,因为下面和右面可能越界!!!!!如果在最右边或者最下面,就会越界),以后要注意这个想法,很实用

class Solution {public:    int islandPerimeter(vector<vector<int>>& grid) {        if (grid.empty() || grid[0].empty()) return 0;        int res = 0, m = grid.size(), n = grid[0].size();        for (int i = 0; i < m; ++i) {            for (int j = 0; j < n; ++j) {                if (grid[i][j] == 0) continue;                res += 4;                if (i > 0 && grid[i - 1][j] == 1) res -= 2;//看上面有没有1,有的话减去重合的2个边                if (j > 0 && grid[i][j - 1] == 1) res -= 2;//看下面有没有1,有的话减去重合的2个边            }        }        return res;    }};

参考资料:
http://www.cnblogs.com/grandyang/p/6096138.html

0 0
原创粉丝点击