摘要:from collections import dequedef orangesRotting(grid):rows, cols = len(grid), len(grid[0])queue = dequefresh_count = 0# 初始化队列和计数fo
腐烂的橘子问题要求我们计算将所有新鲜橘子腐烂所需的最短时间。如果无法腐烂所有橘子,则返回 -1。
Python
from collections import dequedef orangesRotting(grid):rows, cols = len(grid), len(grid[0])queue = dequefresh_count = 0# 初始化队列和计数for r in range(rows):for c in range(cols):if grid[r][c] == 2:queue.append((r, c, 0)) # (row, col, time)elif grid[r][c] == 1:fresh_count += 1# BFS 遍历minutes = 0directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]while queue:r, c, minutes = queue.popleftfor dr, dc in directions:nr, nc = r + dr, c + dcif 0C++
#include #include #include #include using namespace std;// 腐烂的橘子函数int orangesRotting(vector>& grid) {int rows = grid.size, cols = grid[0].size;queue> q;int fresh_count = 0, minutes = 0;// 初始化队列和计数for (int r = 0; r
> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};// BFS 遍历while (!q.empty && fresh_count > 0) {int size = q.size;for (int i = 0; i = 0 && nr = 0 && nc > parseInput(string input) {vector> grid;input = input.substr(1, input.size - 2); // 去掉首尾的方括号stringstream ss(input);string row;while (getline(ss, row, ']')) {if (row.empty) continue;row = row.substr(row.find('[') + 1); // 找到每行的起始stringstream rowStream(row);vector nums;string num;while (getline(rowStream, num, ',')) {nums.push_back(stoi(num));}grid.push_back(nums);}return grid;}int main {cout > grid = parseInput(input);int result = orangesRotting(grid);cout
来源:生酸甜苦辣咸是生活