Young Devs Bin
๐Ÿ“ Today I Learned

Grid BFS in One Day: Islands, Rotting Oranges, Flood Fill, and Three Silent Bugs

ยท2 min readยท#today-i-learned#algorithm#bfs#leetcode#python

Started grinding LeetCode for interview prep. Day one was grid BFS: Number of Islands, Max Area of Island, Rotting Oranges, and Flood Fill. One skeleton, four twists.

  • Mark a cell visited the moment you enqueue it, not when you dequeue it โ€” mark on dequeue and the same cell can pile up in the queue multiple times before it's ever processed
  • Counting islands is just: scan every cell, and every time you hit unvisited land, that's a new island โ€” BFS from there so it never gets counted again
  • Max Area of Island is the exact same code, it just returns the island's size instead of counting
  • Rotting Oranges is multi-source BFS โ€” throw every rotten orange in the queue before the loop starts, then process it one minute (one queue "level") at a time
  • Three ways to mark a cell visited: a separate set, overwriting the grid value, or painting a new color in Flood Fill โ€” same idea, different storage
  • Flood Fill's one real trap: if the new color is the same as the old one, nothing changes, so nothing ever gets marked โ€” infinite loop unless you return early
  • Recursive DFS can go stack-deep on a long snake-shaped island; BFS's queue never gets that deep โ€” worth mentioning out loud in an interview
  • Hit three silent bugs today: compared to the string '1' on an integer grid, enqueued the wrong cell, and typed == where I meant = โ€” all three were quiet, no errors, just wrong answers