A rectangular garden plot of width N and length M of meters is divided into squares with a side of 1 meter. On this site beds are dug up. A bed is a set of squares that satisfies such conditions:
- from any square of this bed you can get into any other square of the same bed,
-consistently moving along the row from square to square through their common side;
-No two beds do not intersect and do not touch each other either on the vertical or horizontal sides of the squares (touching the beds by the corners of the squares is allowed).
Count the number of beds in the garden.
Input data:
5 10 ##......#. .#..#...#. .###....#. ..##....#. ........#. Additional modules do not use.
The first line contains the numbers N and M separated by a space, followed by N lines with M characters. The symbol # indicates the territory of the beds, the dot corresponds to the unoccupied territory. No other characters. (1 ≤ N, M ≤ 200)
The main problem is that the code is checked on the site , where it is checked on 12 tests. Test conditions are not specified, but at the same time they all fail to pass ...
My best bet: 11 of 12:
try: n, m = input().split() n = int(n) m = int(m) alll = [[] for i in range(n)] visited = [[False for j in range(m)] for i in range(n)] num = 0 for i in range(n): row = list(input()) for j in range(m): alll[i].append(row[j]) def dfs(x, y): visited [x][y]= True for dx, dy in [[-1, 0], [0, -1], [0, 1], [1, 0]]: if 0 <= x + dx <= n-1 and 0 <= y + dy <= m-1: if alll[x + dx][y + dy] == "#" and not visited[x + dx][y + dy]: dfs(x + dx, y + dy) for x in range(n): for y in range(m): if alll [x][y]== "#" and not visited[x][y]: dfs(x, y) num += 1 except Exception: num += 1 print(num) there are more: 10 out of 12:
def solve1(N, M, case): l = [[0] * M for i in range(N)] n = 0 connected = set() for i in range(N): for j in range(M): x = 0 if case[i][j] == '#': if (i > 0 and l[i-1][j] != 0): x = l[i-1][j] left = l[i][j-1] if (j > 0 and left != 0): if x != left: if x > 0: connected.add(frozenset((x, left))) else: x = left if x == 0: n += 1 x = n l[i][j] = x #print('\n'.join(str(r) for r in case)) #print('\n'.join(str(r) for r in l)) #print(connected) return n - len(connected) N, M = map(int, input().split()) case = [ list(input()) for _ in range(N) ] print(solve1(N, M, case)) I would be glad to constructive criticism. Thanks for attention)