leetcode 463. Island Perimeter

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:

寫程序之前可以想好測試用例,包括無效輸入,正常輸入,以及一些特殊的輸入。無效輸入包括空數組,正常輸入爲一些m x n 的二維數組, 特殊輸入爲1 x n 或 m x 1 一維數組,或以及1 x 1 的單個 數字。

思路:
首先讀懂題意,題目需要我們計算水中陸地的周長。將問題抽象爲矩陣後,我們只需要考慮矩陣中每個元素值爲1元素的周圍四個元素,不同情況將對陸地周長有不同的影響,下面分情況討論:

  1. 周圍四個元素都爲1,則對周長無影響;
  2. 周圍四個元素中有3個元素爲1,則周長加1;
  3. 周圍四個元素中有2個元素爲1,則周長加2;
  4. 周圍四個元素中有1個元素爲1,則周長加3;
  5. 周圍四個元素都不爲1,則周長加4;

    總的來說,周長可由每個值爲1的元素貢獻疊加得到,每個元素的貢獻值又由四個周圍元素得到,假設四個元素中有x個值爲0,則貢獻爲x,因此周長 =

    i=0j=0(4(xi1,j+xi+1,j+xi,j1+xi,j+1))

    注意,若元素在矩陣邊界,則超出邊界範圍的元素值可假設爲0,爲了避免處理邊界情況,可以在矩陣周圍添加一圈元素值爲0的元素。

最後分析一下算法的複雜度,該算法只需要遍歷二維數組一次,因此時間複雜度爲O(mn)。

有了完整的思路,我們就能寫出程序了。

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        if(grid.size() == 0) return 0;
        int res = 0;
        int row_size = grid.size();
        int col_size = grid[0].size();
        for(int row = 0;row < row_size;++row)
            for(int col = 0;col < col_size;++col)
                {   if(!grid[row][col]) 
                        continue;
                    int count_zero = 0;
                    count_zero += (row - 1 < 0)?1:(!grid[row - 1][col]);
                    count_zero += (row + 1 > row_size - 1)?1:(!grid[row + 1][col]);
                    count_zero += (col - 1 < 0)?1:(!grid[row][col - 1]);
                    count_zero += (col + 1 > col_size - 1)? 1:(!grid[row][col + 1]);
                    res += count_zero;
                }
        return res;
    }
};
發佈了31 篇原創文章 · 獲贊 26 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章