Skip to content

Commit cadb1bd

Browse files
committed
Matrix-Graphs -easy- island perimeter implementation using recursive bfs
1 parent 56ce06f commit cadb1bd

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

matrix/easy/island_perimeter.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def islandPerimeter(self, grid: List[List[int]]) -> int:
6+
rows = len(grid)
7+
cols = len(grid[0])
8+
9+
visited = []
10+
for i in range(rows):
11+
visited.append([0] * cols)
12+
13+
def perm(x, y):
14+
15+
if x < 0 or x > rows - 1 or y < 0 or y > cols - 1 or grid[x][y] == 0:
16+
return 1
17+
18+
if visited[x][y]:
19+
return 0
20+
21+
visited[x][y] = 1
22+
23+
return perm(x - 1, y) + perm(x + 1, y) + perm(x, y + 1) + perm(x, y - 1)
24+
25+
X, Y = 0, 0
26+
for i in range(rows):
27+
for j in range(cols):
28+
if grid[i][j] == 1:
29+
X, Y = i, j
30+
break
31+
res = perm(X, Y)
32+
return res

0 commit comments

Comments
 (0)