Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1ceb16f

Browse files
author
Pranav Bhat
committed
Finding the number of islands
1 parent 713ed93 commit 1ceb16f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
2+
from unittest import main, TestCase
3+
4+
5+
def printMatrix(mat):
6+
print('-----------------------------')
7+
for row in mat:
8+
print(row)
9+
10+
11+
def visit(visited, i, j, mi, mj, mat):
12+
if i < mi and j < mj:
13+
visited[i][j] = True
14+
nr = [-1, -1, -1, 0, 0, 1, 1, 1]
15+
nc = [-1, 0, 1, -1, 1, -1, 0, 1]
16+
for ro in nr:
17+
for co in nc:
18+
r = i + ro
19+
c = j + co
20+
if r >= 0 and r < mi and c >= 0 and c < mj and not visited[r][c] and mat[r][c]:
21+
visited = visit(visited, r, c, mi, mj, mat)
22+
return visited
23+
24+
25+
def findNumberOfIslands(mat):
26+
visited = [[False for k in mat[0]] for p in mat]
27+
count = 0
28+
rows = len(mat)
29+
cols = 0
30+
if rows:
31+
cols = len(mat[0])
32+
for i in range(rows):
33+
for j in range(cols):
34+
if mat[i][j] and not visited[i][j]:
35+
count += 1
36+
visited = visit(visited, i, j, rows, cols, mat)
37+
return count
38+
39+
40+
class CodeTest(TestCase):
41+
def testEmpty(self):
42+
self.assertEqual(findNumberOfIslands([]), 0)
43+
44+
def testNoIslands(self):
45+
mat = [
46+
[0, 0, 0, 0, 0, 0] * 8
47+
]
48+
self.assertEqual(findNumberOfIslands(mat), 0)
49+
50+
def testSquare(self):
51+
mat = [[1, 1, 0, 0, 0],
52+
[0, 1, 0, 0, 1],
53+
[1, 0, 0, 1, 1],
54+
[0, 0, 0, 0, 0],
55+
[1, 0, 1, 0, 1]]
56+
self.assertEqual(findNumberOfIslands(mat), 5)
57+
58+
59+
main()

0 commit comments

Comments
 (0)