# \#463 Island Perimeter
## *給定一個二維陣列grid表示一座陸地和海水, 陣列元素1=陸地, 0=海水, 回傳該陣列的陸地周長(已知沒有湖泊)*
## Log
- build 20210903 by syhuang
## 優化
- 當遇到陸地時, 周長+4
- 檢查右方和下方, 如果也是陸地就-2(因迴圈按順序往右往下, 只需檢查右和下的元素)
- leetcode submit runtime 32%, memory 22%
```javascript=
var islandPerimeter = function(grid) {
let result = 0;
for(let row=0; row<grid.length; row++){
for(let col=0; col<grid[0].length; col++){
if(grid[row][col]==0) continue;
result += 4;
//右
if(row<grid.length-1 && grid[row+1][col]==1) result-=2;
//下
if(col<grid[0].length-1 && grid[row][col+1]==1) result-=2;
}
}
return result;
};
```
## 初見
- 檢查陣列中的每個元素, 當其為陸地(=1)時, 檢查上下左右的元素, 是水的時候周長+1
- leetcode submit runtime 5%, memory 5%
```javascript=
var islandPerimeter = function(grid) {
//檢查每塊陸地的上下左右,只要是水區塊或是邊界,面積+1
let result = 0;
for(let row=0; row<grid.length; row++){
for(let col=0; col<grid[row].length; col++){
if(grid[row][col]==0) continue;
//上
if(typeof(grid[row-1])=='undefined') result++;
else if(grid[row-1][col]==0) result++;
//下
if(typeof(grid[row+1])=='undefined') result++;
else if(grid[row+1][col]==0) result++;
//左
if(typeof(grid[row][col-1])=='undefined') result++;
else if(grid[row][col-1]==0) result++;
//右
if(typeof(grid[row][col+1])=='undefined') result++;
else if(grid[row][col+1]==0) result++;
}
}
return result;
};
```
## 備註
## 參考
- [參考解](https://leetcode.com/problems/island-perimeter/discuss/94992/Java-9-line-solution-add-4-for-each-land-and-remove-2-for-each-internal-edge)
- [另一種](https://leetcode.com/problems/island-perimeter/discuss/95001/clear-and-easy-java-solution)計算陸地數和相鄰數的解
###### tags: `leetcode`, `leetcode-easy`, `application problem`