国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LeetCode題解:Island Perimeter

2019-11-14 09:37:23
字體:
來源:轉載
供稿:網友

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.

思路:

每個點的邊為4,相鄰的兩個點共享一條邊,所以每次碰到連接處,邊的個數減去2。我們從左上掃到右下,所以可以只考慮右邊和下邊的邊。

題解:

int islandPerimeter(const std::vector<std::vector<int>>& grid) {    const size_t M = grid.size();    const size_t N = grid[0].size();    int perimeter(0);    for(size_t i = 0; i < M; ++i) {        for(size_t j = 0; j < N; ++j) {            if (grid[i][j]) {                perimeter += 4;                if (i != M - 1 && grid[i + 1][j]) perimeter -= 2;                if (j != N - 1 && grid[i][j + 1]) perimeter -= 2;            }        }    }    return perimeter;}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 榕江县| 寿阳县| 自治县| 桑日县| 桃园县| 荆门市| 松原市| 泰和县| 南溪县| 尖扎县| 柯坪县| 吴江市| 赤壁市| 台江县| 沈阳市| 金沙县| 舟曲县| 招远市| 白山市| 台中县| 德化县| 永靖县| 江山市| 永泰县| 昌宁县| 涞源县| 攀枝花市| 苍山县| 霍州市| 阳谷县| 高台县| 达拉特旗| 名山县| 科技| 金华市| 平邑县| 淳化县| 安福县| 阿图什市| 荔浦县| 徐汇区|