# Island Perimeter | LeetCode | Solution Explained

463. Island Perimeter is an easy problem on LeetCode. I explore the Iterative solution and the depth first search (dfs) solution. Problem link

Contents

## Iterative Solution

• Each land cell adds 4 to the perimeter
• We remove 1 from its preimeter when the cell in neighbourhood is
• existing
• and is also a land cell
```class Solution:
def islandPerimeter(self, grid: List[List[int]]) -&gt; int:
m, n = len(grid), len(grid)
ans = 0

for x in range(m):
for y in range(n):
if not grid[x][y]: continue # if 0, skip
# now we are looking at a land cell
ans += 4
# the below removes 1 for every land cell in neighbourhood
if x &gt; 0 and grid[x-1][y]: ans -= 1
if x &lt; m-1 and grid[x+1][y]: ans -= 1
if y &gt; 0 and grid[x][y-1]: ans -= 1
if y &lt; n-1 and grid[x][y+1]: ans -= 1

return ans```

## DFS Solution

• mostly the same logic
• change: instead of checking the status of neighbours (out of bounds or water), we go to the neighbour
```class Solution:
def islandPerimeter(self, grid: List[List[int]]) -&gt; int:
m, n = len(grid), len(grid)

def dfs(x, y):
if not (0 &lt;= x &lt;= m-1 and 0 &lt;= y &lt;= n-1): return 1
if grid[x][y] == 0: return 1
if grid[x][y] == -1: return 0
grid[x][y] = -1

count = 0
count += dfs(x+1, y)
count += dfs(x-1, y)
count += dfs(x, y+1)
count += dfs(x, y-1)

return count

for x in range(m):
for y in range(n):
if grid[x][y]:
return dfs(x, y)```
##### Tanishq Chaudhary Producing high-quality intuitive explanations of interview problems. Currently covering LeetCode and InterviewBit.

### Recommended Posts

May 13, 2022

May 12, 2022

##### Reverse integer | InterviewBit | LeetCode | Solution Explained

January 24, 2022

This site uses Akismet to reduce spam. Learn how your comment data is processed.