本文主要是介绍Leetcode——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.
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:
解答
题目让求周长(perimeter)
两种方案:
1。寻找规律,边的个数等于4*island-2*neightbour
注意,这里的neighbour是指右邻居(右边有island)和下邻居(下边有island)。每一个邻居相当于抵消2条边。
下面的理解很直观
+--+ +--+ +--+--+
| | + | | -> | |
+--+ +--+ +--+--+
2。 DFS
代码
class Solution {//use the pattern,the result is "islands * 4 - neighbours * 2",which neighbour refers to the right and down neighbour of the island.
public:int islandPerimeter(vector<vector<int>>& grid) {if(grid.size()==0) return 0;int island=0,neighbour=0;for(int i=0;i<grid.size();i++){for(int j=0;j<grid[0].size();j++){if(grid[i][j]==1) {island++;if(i<grid.size()-1&&grid[i+1][j]==1) neighbour++;if(j<grid[0].size()-1&&grid[i][j+1]==1) neighbour++;}}}/*for(int i=0;i<grid.size()-1;i++)//This is not right, because either i or j can reach the end.{for(int j=0;j<grid[0].size()-1;j++){if(grid[i][j]==1&&grid[i+1][j]==1) neighbour++;if(grid[i][j]==1&&grid[i][j+1]==1) neighbour++;}}*/return 4*island-neighbour*2;}
};
class Solution1 {//use the pattern,the result is "islands * 4 - neighbours * 2",which neighbour refers to the right and down neighbour of the island.
public:int islandPerimeter(vector<vector<int>>& grid) { //grid passed in should be &(cite)if(grid.size()==0) return 0;for(int i=0;i<grid.size();i++){for(int j=0;j<grid[0].size();j++){if(grid[i][j]==1) return helper(grid,i,j);}}return 0;}
private:int helper(vector<vector<int>> &grid,int i,int j)//{int count=0;grid[i][j]=-1; //set the value of grid[i][j] -1,in order to avoiding repeating visitif(i-1<0||grid[i-1][j]==0) count++;else if(grid[i-1][j]==1) count+=helper(grid,i-1,j);if(i+1>=grid.size()||grid[i+1][j]==0) count++;else if(grid[i+1][j]==1) count+=helper(grid,i+1,j);if(j-1<0||grid[i][j-1]==0) count++;else if(grid[i][j-1]==1) count+=helper(grid,i,j-1);if(j+1>=grid[0].size()||grid[i][j+1]==0) count++;else if(grid[i][j+1]==1) count+=helper(grid,i,j+1);return count;}
};
这篇关于Leetcode——463. Island Perimeter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!