Be attention to the usage of recursion, especially the push and pop operation of context (use return function in a suitable time).
Some tricks are used in this task.
(1) expand the matrix in order to avoid list boundary access violation
(2) use another matrix (traversed_mask) to avoid re-filling the region
--
Source code is listed as follows.
#flood fill algorithm
def get_dim(matrix):
return len(matrix[0])
def expand_matrix(dim, matrix):
ll_expanded_matrix = [ ]
l_expanded_row = []
for i in range(0, dim):
l_expanded_row.append(-1)
ll_expanded_matrix.append(l_expanded_row)
l_expanded_row = [-1] #point to another new list
for row in range(0, dim-2): #because dim is for expanded matrix
for col in range(0, dim-2):
l_expanded_row.append(matrix[row][col])
l_expanded_row.append(-1) #tail -1
ll_expanded_matrix.append(l_expanded_row)
l_expanded_row = [-1] #point to another new list
for i in range(0, dim):
l_expanded_row.append(-1)
ll_expanded_matrix.append(l_expanded_row)
return ll_expanded_matrix
def gen_traversed_mask(dim):
l_mask = [ ]
ll_mask = [ ]
for row in range(0, dim):
for col in range(0, dim):
l_mask.append(0)
ll_mask.append(l_mask)
l_mask = [ ]
return ll_mask
def is_same_union(x, y, matrix):
if matrix[y][x] == matrix[y-1][x] or matrix[y][x] == matrix[y+1][x] or matrix[y][x] == matrix[y][x+1] or matrix[y][x] == matrix[y][x-1]:
return True
else:
return False
def flood(x, y, target, dim, traversed_mask, matrix, count):
if x > 0 and x < dim - 1 and y > 0 and y < dim - 1 and traversed_mask[y][x] == 0:
if matrix[y][x] == target and is_same_union(x, y, matrix) == True:
count += 1
else:
return count
traversed_mask[y][x] = 1
count = flood(x-1, y , target, dim, traversed_mask, matrix, count)
count = flood(x+1, y , target, dim, traversed_mask, matrix, count)
count = flood(x , y-1, target, dim, traversed_mask, matrix, count)
count = flood(x , y+1, target, dim, traversed_mask, matrix, count)
return count
def checkio(matrix):
count = 0
ll_result = [ ]
dim = get_dim(matrix)+2 # add two for expanded matrix
expanded_matrix = expand_matrix(dim, matrix)
traversed_mask = gen_traversed_mask(dim)
for row in range(1, dim-1):
for col in range(1, dim-1):
count = flood(col, row, expanded_matrix[row][col], dim, traversed_mask, expanded_matrix, count)
ll_result.append([count, expanded_matrix[row][col]])
traversed_mask = gen_traversed_mask(dim)
count = 0
ll_result = sorted( ll_result, key=lambda l_result: l_result[0], reverse=True)
return ll_result[0]
沒有留言:
張貼留言