fork download
  1. from collections import deque
  2. from sys import stdin
  3.  
  4. di = [-1, -1, -1, 0, 0, 1, 1, 1]
  5. dj = [-1, 0, 1, -1, 1, -1, 0, 1]
  6.  
  7. def bfs(v):
  8. q = collections.deque()
  9. q.append(v)
  10.  
  11. while q:
  12. v = q.popleft()
  13. for a in range(8):
  14. i = v[0] + di[a]
  15. j = v[1] + dj[a]
  16.  
  17. if 0 <= i <= h-1 and 0 <= j <= w-1 and ocean[i][j]:
  18. ocean[i][j] = 0
  19. q.append([i,j])
  20.  
  21. while True:
  22. w, h = map(int, stdin.readline().split())
  23. print(w, h)
  24. if w == 0 and h == 0:
  25. break
  26. ocean = [list(map(int, stdin.readline().split())) for _ in range(h)]
  27. cnt = 0
  28.  
  29. for i in range(h):
  30. for j in range(w):
  31. if ocean[i][j]:
  32. cnt += 1
  33. bfs([i,j])
  34.  
  35. print(cnt)
Runtime error #stdin #stdout #stderr 0.11s 23744KB
stdin
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
stdout
1 1
0
2 2
stderr
Traceback (most recent call last):
  File "./prog.py", line 33, in <module>
  File "./prog.py", line 8, in bfs
NameError: name 'collections' is not defined