Given a 2d grid map of '1'
s (land) and '0'
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110 11010 11000 00000
Answer: 1
Example 2:
11000 11000 00100 00011
使用并查集的数据结构实现这个问题
查找:
def find(m):
if m!=zuxian[m]:
zuxian[m]=find(zuxian[m])
return zuxian[m]
用一个递归的过程,及时更新每个节点新的祖先
合并:
def union():
for i
in range(
self.num):
r,c=i/
self.col,i%
self.col
if grid[r][c]!=
'0':
if r!=
0
and c!=
0
and grid[r-
1][c]==
'1'
and grid[r][c-
1]==
'1':
zuxian[i]=zuxian[find((r-
1)*
self.col+c)]=zuxian[find(r*
self.col+c-
1)]=min([find((r-
1)*
self.col+c),find(r*
self.col+c-
1)])
else:
if r!=
0
and grid[r-
1][c]==
'1':
zuxian[i]=find((r-
1)*
self.col+c)
if c!=
0
and grid[r][c-
1]==
'1':
zuxian[i]=find(r*
self.col+c-
1)
for i
in range(
self.num):
zuxian[i]=find(i)
if grid[i/
self.col][i%
self.col]==
'1'
else -
1
注意的是,当俩个相邻节点的祖先不同时,应该更新节点的祖先的祖先。
最后,可能有某些节点的祖先还没更新到,集中处理一下
全部代码:
class Solution(object):
def numIslands(self, grid):
def initial():
for i
in range(
self.num):
zuxian[i]=i
if grid[i/
self.col][i%
self.col]==
'1'
else -
1
def find(m):
if m!=zuxian[m]:
zuxian[m]=find(zuxian[m])
return zuxian[m]
def union():
for i
in range(
self.num):
r,c=i/
self.col,i%
self.col
if grid[r][c]!=
'0':
if r!=
0
and c!=
0
and grid[r-
1][c]==
'1'
and grid[r][c-
1]==
'1':
zuxian[i]=zuxian[find((r-
1)*
self.col+c)]=zuxian[find(r*
self.col+c-
1)]=min([find((r-
1)*
self.col+c),find(r*
self.col+c-
1)])
else:
if r!=
0
and grid[r-
1][c]==
'1':
zuxian[i]=find((r-
1)*
self.col+c)
if c!=
0
and grid[r][c-
1]==
'1':
zuxian[i]=find(r*
self.col+c-
1)
for i
in range(
self.num):
zuxian[i]=find(i)
if grid[i/
self.col][i%
self.col]==
'1'
else -
1
def totalzuxian():
result=set()
for i
in range(
self.num):
if zuxian[i]>=
0:
result.add(zuxian[i])
return len(result)
if grid==[]:
return
0
self.row,
self.col=len(grid),len(grid[
0])
self.num=
self.row*
self.col
zuxian=[
0]*
self.num
initial()
union()
return totalzuxian()
g=[
'11110',
'11010',
'11000',
'00000']
gg=[
'11000',
'11000',
'00100',
'00011'
]
ggg = [
'10111',
'10101',
'11101']
s=Solution()
print s.numIslands(ggg)