【问题标题】:Rotting orange problem - cannot get expected value腐烂的橙色问题 - 无法获得预期值
【发布时间】:2020-11-01 13:31:55
【问题描述】:

所以给定一篮子nm列的问题,找出所有橙子腐烂所需的最少天数,知道总有至少篮子里有 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


【解决方案1】:

解说视频在这里:https://www.youtube.com/watch?v=1dWTasnWs-M&ab_channel=yilmazbingol

class Solution:
    def __init__(self):
        self.directions=[
                    [-1, 0], 
                    [0, 1], 
                    [1, 0], 
                    [0, -1],
                    ]
    def orangesRotting(self, grid: List[List[int]]) -> int:
        fresh_oranges=0
        queue=deque()
        ROWS,COLS=len(grid),len(grid[0])
        # get the initial state of the grid
        for i in range(ROWS):
            for j in range(COLS):
                if grid[i][j]==1:
                    fresh_oranges+=1
                if grid[i][j]==2:
                    queue.append((i,j))
        minutes=0
        current_batch_size=len(queue)
        # process all the bad oranges
        while queue:
            # 1 minute passes when i process each batch
            if current_batch_size==0:
                minutes+=1
                current_batch_size=len(queue)
            current_orange=queue.popleft()
            current_row=current_orange[0]
            current_col=current_orange[1]
            current_batch_size-=1
            # check the neighbors of current_orange
            for direction in self.directions:
                next_row=current_row+direction[0]
                next_col=current_col+direction[1]
                if next_row<0 or next_row==ROWS or next_col<0 or next_col==COLS:
                    continue
                # if next orange is fresh, convert to a bad orange
                if grid[next_row][next_col]==1:
                    grid[next_row][next_col]=2
                    fresh_oranges-=1
                    queue.append((next_row,next_col))
        if fresh_oranges!=0:
            return -1
        return minutes
            
        
        
            
        
            
    
                    
                    
                

【讨论】:

    【解决方案2】:

    您的程序基于索引。如果 Position 为 [[2,4]],则索引位置为 [[1, 3]]。如果您提供索引位置作为输入,或者您可以将位置转换为程序内的索引位置,您将获得预期的输出 4。

    还可以找到解决问题的不同方法。

    def get_neb_pos_list(r_lim, c_lim, r_pos):
            neb_list = [(r_pos[0] + 1, r_pos[1]) if r_pos[0] + 1 < r_lim else (r_pos[0], r_pos[1])] + \
                       [(r_pos[0] - 1, r_pos[1]) if r_pos[0] - 1 >= 0 else (r_pos[0], r_pos[1])] + \
                       [(r_pos[0], r_pos[1] + 1) if r_pos[1] + 1 < c_lim else (r_pos[0], r_pos[1])] + \
                       [(r_pos[0], r_pos[1] - 1) if r_pos[1] - 1 >= 0 else (r_pos[0], r_pos[1])]
       return neb_list
    
    
    def get_min_days_to_rot(n_rows, n_cols, r_pos):
        oranges = [(i, j) for i in range(n_rows) for j in range(n_cols)]
        if r_pos[0] not in oranges:
            return "Invalid Position"
        if n_rows <= 0 or n_cols <= 0:
            return "Invalid number of rows or columns"
        if len(oranges) == 1:
            return 0
        rot_oranges = list(r_pos)
        n_days = 0
        while len(rot_oranges) < n_rows * n_cols:
            for pos in r_pos:
                rot_list = get_neb_pos_list(n_rows, n_cols, pos)
                rot_oranges.extend(rot_list)
            rot_oranges = list(set(rot_oranges))
            r_pos = list(rot_oranges)
            n_days += 1
        return n_days
    
    
    if __name__ == "__main__":
        n = 3
        m = 7
        pos = [(1,3)]
        n_days = get_min_days_to_rot(n, m, pos)
        print(n_days)
    

    【讨论】:

      猜你喜欢
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2016-10-01
      相关资源
      最近更新 更多