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:
class Solution {
public:
    int neighborNum(vector<vector<int>>& grid, int row, int col)
    {
    int num = 0;
    if (row > 0 && grid[row-1][col] == 1) {
    num++;
    }
    if (row+1 < grid.size() && grid[row + 1][col] == 1) {
    num++;
    }
    if (col+1 < grid[0].size() && grid[row][col+1] == 1) {
    num++;
    }
    if (col > 0 && grid[row][col - 1] == 1) {
    num++;
    }
    return num;
    }
    
    int islandPerimeter(vector<vector<int>>& grid) {
    int perimeter = 0;
    for (int row = 0; row < grid.size(); row++)
    {
    for (int col = 0; col < grid[row].size(); col++)
    {
    if (grid[row][col] == 1) {
    perimeter += 4 - neighborNum(grid, row, col);
    }
    }
    }
    return perimeter;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章