defMyPrint(t): for i inrange(1, t): print(a[i], end='+') print(a[t], end='\n')
defdfs(s, t): # s表示要拆分的数,t来确定a数组的索引 for i inrange(a[t-1], s+1): if i < n: # 防止输出n自身 a[t] = i s -= i if s == 0: MyPrint(t) else: dfs(s, t+1) s += i # 进行回溯以输出所有可能的结果
if __name__ == '__main__': n = int(input()) a = [1] * 1000# 开辟储存拆分结果的数组
Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (‘.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors. Given a diagram of Farmer John’s field, determine how many ponds he has.
输入格式
Line 1: Two space-separated integers: N and M * Lines 2..N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
输出格式
Line 1: The number of ponds in Farmer John’s field.
defdfs(x, y): geo[x][y] = '.' for i inrange(8): nx = x + dir_x[i] ny = y + dir_y[i] if nx < 0or nx >= n or ny < 0or ny >= m or geo[nx][ny] == '.': continue dfs(nx, ny)
if __name__ == '__main__': n, m = map(int, input().split()) geo = [[''for i inrange(101)] for i inrange(101)] for i inrange(n): string = input() for j inrange(m): geo[i][j] = string[j]
count = 0 for i inrange(n): for j inrange(m): if geo[i][j] == 'W': dfs(i, j) count += 1
首先要介绍的是setrecursionlimit()函数,这个函数可以用来设置最大递归深度,可以用来避免RuntimeError: Maximum recursion depth exceeded类型的报错。