Advertisement
simeonshopov

Hungry Hipos

Jan 23rd, 2020
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. #!/usr/local/bin/python3.7
  2. # -*- coding: utf-8 -*import
  3.  
  4. def valid(y,x):
  5.     if y>=0 and x>=0 and y<N and x<horizontal_len:
  6.         return True
  7.  
  8. def find_blocks(y,x):
  9.     Q.append(y)
  10.     Q.append(x)
  11.  
  12.     dy = [0,1,0,-1]
  13.     dx = [1,0,-1,0]
  14.  
  15.     while Q:
  16.         y = Q.pop(0)
  17.         x = Q.pop(0)
  18.  
  19.         for dir in range(len(dy)):
  20.             next_y = y + dy[dir]
  21.             next_x = x + dx[dir]
  22.  
  23.             if valid(next_y,next_x) and matrix[next_y][next_x] == 1:
  24.                 Q.append(next_y)
  25.                 Q.append(next_x)
  26.                 matrix[next_y][next_x] = -1
  27.  
  28.  
  29. N = int(input())
  30.  
  31. matrix = []
  32. for rows in range(N):
  33.    row = list(map(int, input().split()))
  34.    matrix.append(row)
  35.  
  36. horizontal_len = len(matrix[0])
  37.  
  38. blocks = 0
  39.  
  40. for start_y in range(N):
  41.     for start_x in range(horizontal_len):
  42.  
  43.         if matrix[start_y][start_x] == 1:
  44.             matrix[start_y][start_x] = -1
  45.             Q=[]
  46.  
  47.             find_blocks(start_y, start_x)
  48.             blocks +=1
  49.  
  50. print(blocks)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement