1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| def calcCommonRestaurants(grid): m, n = len(grid), len(grid[0]) startPoints = [] for i in range(m): for j in range(n): if grid[i][j] == 2: startPoints.append((i, j)) restSet1 = dfs(grid, startPoints[0][0], startPoints[0][1]) restSet2 = dfs(grid, startPoints[1][0], startPoints[1][1])
commonRestaurants = restSet1.intersection(restSet2) return len(commonRestaurants)
def dfs(grid, i, j): m, n = len(grid), len(grid[0]) visited = set() visited.add((i, j)) restaurants = set() queue = [(i, j)]
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] while queue: x, y = queue.pop() if grid[x][y] == 3: restaurants.add((x, y))
for dx, dy in directions: new_x, new_y = x + dx, y + dy if (0 <= new_x < m and 0 <= new_y < n and grid[new_x][new_y] != 1 and (new_x, new_y) not in visited): visited.add((new_x, new_y)) queue.append((new_x, new_y))
return restaurants
if __name__ == '__main__': m, n = map(int, input().split()) grid = [list(map(int, input().split())) for _ in range(m)]
commonRestaurants = calcCommonRestaurants(grid)
print(commonRestaurants)
|