8000
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ebae6e7 commit b96c53fCopy full SHA for b96c53f
Number_of_Islands.py
@@ -0,0 +1,29 @@
1
+class Solution:
2
+ # @param {boolean[][]} grid a boolean 2D matrix
3
+ # @return {int} an integer
4
+ def numIslands(self, grid):
5
+ count = 0
6
+ self.grid = grid
7
+ for i in xrange(len(grid)):
8
+ for j in xrange(len(grid[0])):
9
+ if grid[i][j] == 1:
10
+ count += 1
11
+ self.dfs(i, j)
12
+ return count
13
+
14
+ # deep first search
15
+ def dfs(self, i, j):
16
+ # validity check
17
+ if i < 0 or j < 0 or i >= len(self.grid) \
18
+ or j >= len(self.grid[0]):
19
+ return
20
+ # cell is water or visited
21
+ if self.grid[i][j] == 0:
22
23
+ # set visited
24
+ self.grid[i][j] = 0
25
+ # begin dfs
26
+ self.dfs(i - 1, j)
27
+ self.dfs(i + 1, j)
28
+ self.dfs(i, j - 1)
29
+ self.dfs(i, j + 1)
0 commit comments