, NP-hard!
NP.
. Flood Fill, , Disjoint-set .
Flood Fill
, N x M, (row, column) null, , .
1..M 1..N. :
for row in range(1, N + 1):
for column in range(1, M + 1):
if matrix[row][column] is not null:
floodfill(matrix, row, column)
Flood Fill , null, Flood Fill .
def floodfill(matrix, row, column):
Q = Queue()
dirs = { (-1, 0), (1, 0), (0, -1), (0, 1) }
Q.push( (row, column) )
matrix[row][column] = null
while Q is not empty:
(r, c) = Q.pop()
region.add( (r, c) )
for (dr, dc) in dirs:
if matrix[r + dr][c + dc] is not null
and r + dr <= rows(matrix)
and c + dc <= colums(matrix):
Q.push(r + dr, c + dc)
matrix[r + dr][c + dc] = null
return region
, , . , , .
, , . floodfill.
def floodfill(matrix):
disjoint_set = DisjointSet()
for row in range(1, N + 1):
for column in range(1, M + 1):
disjoint_set.makeSet(row, column)
if matrix[row - 1][column] is not null:
disjoint_set.merge((row, column), (row - 1, column))
if matrix[row][column - 1] is not null:
disjoint_set.merge((row, column), (row, column - 1))
for row in range(1, N + 1):
for column in range(1, M + 1):
regions[ disjoint_set.find(row, column) ] = (row, column)
return regions
, .
, , .