惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
云风的 BLOG
云风的 BLOG
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
Y
Y Combinator Blog
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Check Point Blog
M
MIT News - Artificial intelligence
Jina AI
Jina AI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
F
Fortinet All Blogs
博客园 - 司徒正美
I
InfoQ
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
U
Unit 42

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Rotting Oranges
Jaspreet singh · 2026-06-28 · via DEV Community

Jaspreet singh

Problem Statement

You are given an m × n grid where:

0 → Empty Cell

1 → Fresh Orange

2 → Rotten Orange

Every minute:

A rotten orange
rots all adjacent
fresh oranges.

Return:

  • Minimum time required to rot all oranges.
  • Return -1 if impossible.

Brute Force Intuition

In an interview, you can explain it like this:

Simulate the process minute by minute. In every minute, scan the entire grid and rot adjacent fresh oranges.

Since the grid is scanned repeatedly, many cells are visited multiple times.

Complexity

  • Time Complexity: O((M × N)²)
  • Space Complexity: O(1)

Brute Force Idea

Repeat

↓

Traverse Entire Grid

↓

Rot Adjacent Fresh Oranges

↓

Continue Until
No Change


Moving Towards the Optimal Approach

Notice something important.

Initially:

Multiple Rotten Oranges

start spreading simultaneously.

Instead of processing one rotten orange after another,

we should process:

All Rotten Oranges Together.

This is exactly:

Multi-Source BFS


Pattern Recognition

Whenever you see:

  • Spread Infection
  • Fire Spread
  • Minimum Time
  • Shortest Distance from Multiple Sources

Think:

Multi-Source BFS


Key Observation

Instead of pushing only one source into the queue,

push:

Every Rotten Orange

at time:

0

Then BFS naturally processes oranges level by level.

Each level represents:

One Minute


Optimal Approach

Step 1

Traverse the grid.

Push every rotten orange into the queue.

Count fresh oranges.


Step 2

Run BFS.

For every rotten orange:

Visit 4 Directions

↓

Rot Fresh Orange

↓

Push into Queue


Step 3

If all fresh oranges become rotten:

Return Time

Otherwise:

Return -1


Optimal Java Solution

class Solution {

    public int orangesRotting(int[][] grid) {

        int rows = grid.length;
        int cols = grid[0].length;

        Queue<int[]> q = new LinkedList<>();

        int fresh = 0;

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < cols; j++) {

                if (grid[i][j] == 2) {

                    q.offer(new int[]{i, j});

                } else if (grid[i][j] == 1) {

                    fresh++;
                }
            }
        }

        if (fresh == 0)
            return 0;

        int minutes = 0;

        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};

        while (!q.isEmpty()) {

            int size = q.size();

            boolean rotten = false;

            for (int i = 0; i < size; i++) {

                int[] cell = q.poll();

                int r = cell[0];
                int c = cell[1];

                for (int d = 0; d < 4; d++) {

                    int nr = r + dr[d];
                    int nc = c + dc[d];

                    if (nr >= 0 &&
                        nc >= 0 &&
                        nr < rows &&
                        nc < cols &&
                        grid[nr][nc] == 1) {

                        grid[nr][nc] = 2;

                        fresh--;

                        rotten = true;

                        q.offer(new int[]{nr, nc});
                    }
                }
            }

            if (rotten)
                minutes++;
        }

        return fresh == 0
                ? minutes
                : -1;
    }
}


Dry Run

Input

2 1 1

1 1 0

0 1 1

Initially:

Queue:

(0,0)

Fresh:

6


Minute 1

Rot:

2 2 1

2 1 0

0 1 1

Queue:

(0,1)

(1,0)


Minute 2

Rot:

2 2 2

2 2 0

0 1 1

Queue:

(0,2)

(1,1)


Minute 3

Rot:

2 2 2

2 2 0

0 2 1


Minute 4

Rot:

2 2 2

2 2 0

0 2 2

Fresh:

0

Answer:

4


Why Multi-Source BFS Works?

All rotten oranges spread simultaneously.

BFS naturally processes:

Level 0

↓

Level 1

↓

Level 2

Each BFS level corresponds to:

One Minute

Thus, the first time a fresh orange is reached is also the minimum time needed to rot it.


Complexity Analysis

Metric Complexity
Time Complexity O(M × N)
Space Complexity O(M × N)

Interview One-Liner

Treat every initially rotten orange as a BFS source and spread the infection level by level to compute the minimum time required to rot all fresh oranges.


Pattern Learned

Multiple Sources

+

Minimum Time

↓

Multi-Source BFS

Similar Problems

  • Rotten Oranges
  • Walls and Gates
  • 01 Matrix
  • Nearest Exit in Maze
  • Shortest Path in Binary Matrix
  • Distance of Nearest Cell Having 1

Memory Trick

Think:

All Rotten Oranges

↓

Push into Queue

↓

Spread Together

↓

Each BFS Level

=

One Minute

Mental Model

One Source

↓

Normal BFS

--------------------

Many Sources

↓

Multi-Source BFS

Whenever you hear:

"Spread simultaneously", "Minimum time to infect", or "Multiple starting points"

your brain should immediately think:

Multi-Source BFS