leetcode——Rotting Oranges

leetcode——Rotting Oranges(python)

题目:
In a given grid, each cell can have one of three values:

the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.

大致思路:
根据图遍历搜素(BFS)
1)计算新鲜橘子的个数,将烂橘子的坐标位置存在一个队列中
2)遍历烂橘子,若其周围四个格子中有新鲜橘子,则把这些新鲜橘子变成烂橘子,并将其坐标位置加在队列后面,一直遍历~
3)若最后烂橘子遍历完了,则结束。若此时新鲜橘子数量不为0,则返回-1;否则返回遍历次数-1.

代码如下:

class Solution(object):
    def orangesRotting(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        M, N = len(grid), len(grid[0])
        fresh = 0
        q = collections.deque()
        for i in range(M):
            for j in range(N):
                if grid[i][j] == 1:
                    fresh += 1
                elif grid[i][j] == 2:
                    q.append((i,j))
        if fresh == 0:
            return 0
        dirs = [(0,1),(0,-1),(1,0),(-1,0)]
        step = 0
        while q:
            size = len(q)
            for i in range(size):
                x, y = q.popleft()
                for d in dirs:
                    nx, ny = x + d[0], y + d[1]
                    if nx < 0 or nx >= M or ny < 0 or ny >= N or grid[nx][ny] != 1:
                        continue
                    grid[nx][ny] = 2
                    q.append((nx,ny))
                    fresh -= 1
            step += 1
        if fresh != 0:
            return -1 
        return step - 1

2019.2.24
学习掌握DFS和BFS

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值