Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@voith
Created December 13, 2019 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voith/4897f80aafbf7a0db9db00d55a5ee37b to your computer and use it in GitHub Desktop.
Save voith/4897f80aafbf7a0db9db00d55a5ee37b to your computer and use it in GitHub Desktop.
total number of connected regions in a grid
class Solution(object):
def __init__(self, matrix, row, col):
self.matrix = matrix
self.row = row
self.col = col
def is_safe(self, i, j, visited):
return (
0 <= i < self.row and
0 <= j < self.col and
not visited[i][j] and
self.matrix[i][j] == "1"
)
def dfs(self, i, j, visited):
row_num = [-1, 0, 0, 1]
col_num = [0, -1, 1, 0]
visited[i][j] = True
for k in range(4):
if self.is_safe(i + row_num[k], j + col_num[k], visited):
self.dfs(i + row_num[k], j + col_num[k], visited)
def num_offices(self):
visited = [[False for j in range(self.col)] for i in range(self.row)]
count = 0
for i in range(self.row):
for j in range(self.col):
if (not visited[i][j]) and (self.matrix[i][j] == "1"):
self.dfs(i, j, visited)
count += 1
return count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment