← Capgemini bank

Capgemini · Question 63

Rotting Oranges

C++code⏱ O(mn)💾 O(mn)
Service-based

Problem

You are given grid with fresh and rotten oranges. Find minimum time for all oranges to rot.

Approach

Multi-source BFS from all rotten oranges, tracking minutes per layer.

Time O(mn)Space O(mn)

How it works

  1. 1Seed the queue with every rotten orange.
  2. 2Each BFS layer rots neighbours: one minute.
  3. 3Leftover fresh means impossible: -1.

Sample input / output

Input:
grid = [[2,1,1],[1,1,0],[0,1,1]]
Output:
4

Constraints

1 <= m, n <= 10; cells 0/1/2.

Solution — read it, then walk it

Time O(mn)Space O(mn)Loops 5Branches 4Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <queue>using namespace stdDEFINEorangesRotting(vector<vector<int>>&grid)DEFINE m = grid.size(), n =grid[0].size()queue<pair<int,int>> qDEFINE fresh = 0for (int i = 0; i < m;i++)for (int j = 0; j < n;j++)if (grid[i][j] == 2)q.push({i, j})if (grid[i][j] == 1)fresh++if (fresh == 0) return0DEFINE minutes = 0vector<vector<int>> dirs ={{-1,0},{1,0},{0,-1},{0,1}}while (!q.empty())DEFINE size = q.size()for (int i = 0; i <size; i++)auto [x, y] = q.front()q.pop()for (auto& dir : dirs)DEFINE nx = x + dir[0], ny= y + dir[1]if (nx >= 0 && nx < m&& ny >= 0 && ny < n&& grid[nx][ny] == 1)grid[nx][ny] = 2fresh--q.push({nx, ny})minutes++RETURN fresh == 0 ? minutes- 1 : -1DEFINE main()vector<vector<int>> grid ={{2,1,1},{1,1,0},{0,1,1}}cout <<orangesRotting(grid) <<endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/33

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits