可以用,但是超时了(Python)
2024-07-28 12:22:06
发布于:浙江
13阅读
0回复
0点赞
def is_valley(grid, x, y, n):
if grid[x][y] == float('inf') or grid[x][y] >= min_adjacent(grid, x, y, n):
return False
stack = [(x, y)]
grid[x][y] = float('inf') # 标记为已访问
size = 1
while stack:
i, j = stack.pop()
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ni, nj = i + di, j + dj
if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] != float('inf'):
if grid[ni][nj] < min_adjacent(grid, ni, nj, n):
stack.append((ni, nj))
grid[ni][nj] = float('inf')
size += 1
return size
def min_adjacent(grid, i, j, n):
values = []
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ni, nj = i + di, j + dj
if 0 <= ni < n and 0 <= nj < n:
values.append(grid[ni][nj])
return min(values) if values else float('inf')
def count_valleys(grid):
n = len(grid)
total_valleys = 0
for i in range(n):
for j in range(n):
if grid[i][j] != float('inf'):
total_valleys += is_valley(grid, i, j, n)
return total_valleys
def main():
n = int(input().strip())
grid = [[float('inf') if c == 'o' else int(c) for c in input().strip()] for _ in range(n)]
print(count_valleys(grid))
if __name__ == '__main__':
main()
田亩得太难了
这里空空如也
有帮助,赞一个