Skip to content

Instantly share code, notes, and snippets.

@alexreyes
Created December 9, 2019 16:15
Show Gist options
  • Save alexreyes/2ab83ed18d0278d81c0194f425404585 to your computer and use it in GitHub Desktop.
Save alexreyes/2ab83ed18d0278d81c0194f425404585 to your computer and use it in GitHub Desktop.
Solution for number of islands problem on leetcode: https://leetcode.com/problems/number-of-islands/
class Solution(object):
def numIslands(self, grid):
if (not grid):
return 0
rowLen = len(grid)
columnLen = len(grid[0])
islandCount = 0
for row in range(rowLen):
for column in range(columnLen):
if (grid[row][column] == '1'):
islandCount+=1
self.bfs(grid, row, column)
return islandCount
def bfs(self, grid, row, column):
queue = collections.deque()
queue.append([row,column])
while (queue):
x,y = queue.popleft()
adjacents = [[x+1, y], [x-1, y], [x,y+1], [x,y-1]]
for adjacent in adjacents:
if (adjacent[0] > -1 and adjacent[0] < len(grid) and adjacent[1] > -1 and adjacent[1] < len(grid[0])):
if grid[adjacent[0]][adjacent[1]] == "1":
grid[adjacent[0]][adjacent[1]] = "0"
queue.append([adjacent[0],adjacent[1]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment