前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 994. Rotting Oranges

Leetcode 994. Rotting Oranges

作者头像
Tyan
发布2021-07-23 16:23:18
2060
发布2021-07-23 16:23:18
举报
文章被收录于专栏:SnailTyan

1. Description

Rotting Oranges
Rotting Oranges

2. Solution

**解析:**Version 1,先统计新鲜水果数量,如果不存在,则时间为0,同时记录腐败水果的位置。按照广度优先搜索,记录下一轮腐败水果的位置,同时时间加1,新鲜水果数量减1,递归执行,直至不存在腐败的水果位置或者新鲜水果为0。如果此时仍存在新鲜水果,则返回-1,否则,返回时间。

  • Version 1
代码语言:javascript
复制
class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        fresh = 0
        rotten = []
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 2:
                    rotten.append([i, j])
                elif grid[i][j] == 1:
                    fresh += 1
        if fresh == 0:
            return 0
        time = 0
        while rotten and fresh:
            temp = []
            for x, y in rotten:
                if x > 0 and grid[x-1][y] == 1:
                    grid[x-1][y] = 2
                    temp.append([x-1, y])
                    fresh -= 1
                if y > 0 and grid[x][y-1] == 1:
                    grid[x][y-1] = 2
                    temp.append([x, y-1])
                    fresh -= 1
                if x < m - 1 and grid[x+1][y] == 1:
                    grid[x+1][y] = 2
                    temp.append([x+1, y])
                    fresh -= 1
                if y < n - 1 and grid[x][y+1] == 1:
                    grid[x][y+1] = 2
                    temp.append([x, y+1])
                    fresh -= 1
            time += 1
            rotten = temp
        if fresh == 0:
            return time
        else:
            return -1

Reference

  1. https://leetcode.com/problems/rotting-oranges/
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/07/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档