【发布时间】:2020-11-01 13:31:55
【问题描述】:
所以给定一篮子n行m列的问题,找出所有橙子腐烂所需的最少天数,知道总有至少篮子里有 1 个烂橙子,它们的位置作为输入嵌套列表 positions 给出。
(编辑:抱歉,忘记添加腐烂规则,但基本上与腐烂的橙子相邻的橙子应该在第二天腐烂,例如如果[1,1]处的橙子今天腐烂,[0,1]处的橙子,[ 2,1]、[1,0]、[1,2] 应该会在第二天腐烂)
只是无法从下面的输入中获得预期的输出,而且我看不到我的代码哪里出错了。真的开始觉得给出的预期输出在某种程度上是有问题的。有一些建议会很棒。
输入:n = 3,m = 7,位置 = [[2,4]]
预期输出:4
实际输出:6
def rottingOrange(n,m,positions):
#Idea: Find cells that have not rotten
#If either cell next to it have rotten, it will also rot
#If there is no more cells that have not rot, stops
def isValid(i,j,positions):
#Determine if an orange position is adjacent to a rotten orange
if [i-1,j] in positions or [i+1,j] in positions or [i,j-1] in positions or [i,j+1] in positions:
return True
else:
return False
def rot(grid,positions):
#Find all oranges that should rot for the current day
temp = []
for i,j in grid:
if isValid(i,j,positions):
temp = temp + [[i,j]]
if len(temp) < 1:
return "cannot rot"
else:
grid_new = [x for x in grid if x not in temp]
positions_new = positions + temp
return grid_new, positions_new
def rotting(grid, positions):
#find the number of days taken to rot all oranges
if len(grid) <= 0 or rot(grid, positions) == "cannot rot":
return 0
else:
grid_new = rot(grid,positions)[0]
positions_new = rot(grid,positions)[1]
if len(grid_new) == len(grid):
return rotting(grid_new,positions_new)
else:
return 1 + rotting(grid_new,positions_new)
def grid_creation(n,m,positions):
#create grid of size n x m, and remove all oranges that have rotten
grid = []
for i in range(n):
for j in range(m):
grid.append([i,j])
for x in positions:
if x in grid:
grid.remove(x)
return grid
if __name__ == "__main__":
grid = grid_creation(n,m,positions)
return rotting(grid,positions)
【问题讨论】:
-
我不认为这可以通过递归有效地解决,尝试使用 BFS 代替所有腐烂的单元格将开始距离为 0 的单元格,然后 BFS 中的最大距离将是答案。递归本质上只是没有找到最短路径的 DFS
-
你能链接到原始挑战吗?通常这个问题的输入是不同的,我想你可能错过了输入中的一个东西。例如,LeetCode 和 GeeksForGeeks 上的同名问题与您在这里告诉我们的不同。
-
"知道篮子里总是至少有 1 个烂橙子,找出所有橙子腐烂所需的最少天数" 说明哪些橙子在哪一天腐烂的规则是什么?
-
抱歉,添加了腐烂橙子的规则,基本上相邻的橙子都应该腐烂了
标签: python python-3.x algorithm recursion