|
| 1 | +// Source : https://leetcode.com/problems/island-perimeter/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2019-02-04 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 |
| 8 | + * represents water. |
| 9 | + * |
| 10 | + * Grid cells are connected horizontally/vertically (not diagonally). The grid is completely |
| 11 | + * surrounded by water, and there is exactly one island (i.e., one or more connected land cells). |
| 12 | + * |
| 13 | + * The island doesn't have "lakes" (water inside that isn't connected to the water around the island). |
| 14 | + * One cell is a square with side length 1. The grid is rectangular, width and height don't exceed |
| 15 | + * 100. Determine the perimeter of the island. |
| 16 | + * |
| 17 | + * Example: |
| 18 | + * |
| 19 | + * Input: |
| 20 | + * [[0,1,0,0], |
| 21 | + * [1,1,1,0], |
| 22 | + * [0,1,0,0], |
| 23 | + * [1,1,0,0]] |
| 24 | + * |
| 25 | + * Output: 16 |
| 26 | + * |
| 27 | + * Explanation: The perimeter is the 16 yellow stripes in the image below: |
| 28 | + * |
| 29 | + ******************************************************************************************************/ |
| 30 | +class Solution { |
| 31 | +public: |
| 32 | + int edge(vector<vector<int>> &grid, int x, int y) { |
| 33 | + int edge = 0; |
| 34 | + |
| 35 | + if (x==0 || (x>0 && grid[x-1][y] == 0 ) ) edge++; //up |
| 36 | + if (y==0 || (y>0 && grid[x][y-1] == 0 ) ) edge++; //left |
| 37 | + if (x == grid.size() - 1 || |
| 38 | + (x < grid.size() - 1 && grid[x+1][y] == 0)) edge++; //down |
| 39 | + if (y == grid[0].size() - 1 || |
| 40 | + (y < grid[0].size() - 1 && grid[x][y+1] == 0)) edge++; //right |
| 41 | + |
| 42 | + return edge; |
| 43 | + } |
| 44 | + |
| 45 | + int islandPerimeter(vector<vector<int>>& grid) { |
| 46 | + int perimeter = 0; |
| 47 | + for(int i=0; i<grid.size(); i++) { |
| 48 | + for(int j=0; j<grid[0].size(); j++) { |
| 49 | + if (grid[i][j] == 1) { |
| 50 | + perimeter += edge (grid, i, j); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + return perimeter; |
| 55 | + } |
| 56 | +}; |
0 commit comments