Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Rishabh Shukla
Another Python BFS solution

Rishabh Shukla

Mar 15, 2024

from collections import deque class Solution: def countClosedIslands(self, matrix): countClosedIslands = 0 self.n = len(matrix) self.m = len(matrix[0]) self.matrix = matrix self.visited = [[False for y in range(self.m)] for x in range(self.n)] for i in range(self.n): for j in range(self.m): if self.matrix[i][j] == 1 and not self.visited[i][j]: is_closed = self.bfs(i, j) if is_closed: countClosedIslands += 1 return countClosedIslands def bfs(self, p, q): queue = deque([(p, q)]) closed = True while queue: row, col = queue.popleft() if row < 0 or row >= self.n or col < 0 or col >= self.m: closed = False continue if self.matrix[row][col] == 0: continue if not self.visited[row][col]: queue.append((row - 1, col)) queue.append((row, col - 1)) queue.append((row + 1, col)) queue.append((row, col + 1)) self.visited[row][col] = True return closed

0

0

Comments
Comments

On this page