小美的新游戏-DFS
小美的新游戏
http://www.nowcoder.com/questionTerminal/79bf0fa54f094f0fb2dee942b1ecc359
使用增量字典减少代码量和判断流程
python可能超过最大递归深度,需要手动设置增大递归深度
import sys sys.setrecursionlimit(100000) n, m, P, Q = map(int, input().strip().split()) grid = [] for i in range(n): grid.append(list(input().strip())) seq = input().strip() dir_map = { 'S':(1, 0), 'W':(-1, 0), 'A':(0, -1), 'D':(0, 1) } def is_valid(i, j): if 0 <= i <n and 0<= j<m and grid[i][j] != '#': return True return False score = 0 def dfs(i, j, t): global score if t == len(seq): return dir_cur = dir_map[seq[t]] newi = i + dir_cur[0] newj = j + dir_cur[1] if is_valid(newi, newj): if grid[newi][newj] == 'X': score -= Q elif grid[newi][newj] == 'O': score += P grid[newi][newj] = '_' dfs(newi, newj, t+1) else: dfs(i, j, t+1) for i in range(n): for j in range(m): if grid[i][j] == 'S': dfs(i, j, 0) print(score) exit()