Learning DFS (Depth-First Search).
As a memorandum, I couldn't understand it from the ant book alone.
You do not have to do .replace ('.', '0'). Replace ('W', '1')
.
2386.py
n,m=map(int,input().split())
a=[list(map(int,list(input().replace('.','0').replace('W','1')))) for i in range(n)]
def dfs(x,y):
a[x][y]=0
for dx in [-1,0,1]:
for dy in [-1,0,1]:
nx=x+dx
ny=y+dy
if 0<=nx<n and 0<=ny<m and a[nx][ny]==1:
dfs(nx,ny)
cnt=0
for i in range(n):
for j in range(m):
if a[i][j]==1:
dfs(i,j)
cnt+=1
print(cnt)
Recommended Posts