Number Of Islands | DFS | Graph - Leetcode 200 Python
Автор: ShivSatty
Загружено: 2025-11-29
Просмотров: 4
Описание:
I have a confession to make.
I spent my entire weekend sinking islands. 🏝️💥
No, I didn’t buy a villain lair in the Pacific. I tackled LeetCode 200: Number of Islands.
If you are new to Data Structures, this problem looks deceptively cute. "Aw, look at the grid! 1s are land, 0s are water. Just count the blobs!"
WRONG.
This problem is a psychological trap designed by Big Tech to see if you can handle recursion without crying.
Here is the diary of my descent into madness (and eventually, the solution):
Phase 1: The Naive Approach 👶 I started iterating through the grid like a civilized human being. I found a '1'. I said, "Hello, Island!" I moved to the next cell. I found another '1'. I counted it again. I realized I had counted the same island 14 times. My island count was higher than the GDP of a small nation.
Phase 2: The Realization 💡 I realized this isn't a "Grid" problem. It's a Graph problem wearing a disguise. The '1's aren't just numbers. They are nodes. And if they are touching, they are family. You can’t just visit them. You have to mark them.
Phase 3: The "Scorched Earth" Strategy (DFS) 🔥 This is where the magic (and the violence) happens. To solve this efficiently in O(M*N), you have to abandon your morals regarding "immutable data."
The algorithm is simple, yet brutal:
Scan the grid until you find land ('1').
Increment your counter.
Immediately launch a Depth-First Search (DFS).
Visit every single connected piece of land and TURN IT INTO WATER ('0').
Yes. You literally sink the island as you count it. By the time you return to your main loop, the island is gone. Erased from history. Why? So you never count it again.
It’s efficient. It’s elegant. It’s slightly sociopathic. But it gets the job offer.
The "BFS vs. DFS" War ⚔️ You can also use BFS (Breadth-First Search). DFS is like diving headfirst into a rabbit hole until you hit the bottom. BFS is like a spreading mold infection. Both work. Both scare me.
In this video breakdown, I cover: ✅ Why your recursion stack keeps overflowing (hint: check your boundary conditions). ✅ The exact logic to "sink" the ships without sinking ship. ✅ Why grid[i][j] = '0' is the most satisfying line of code you will ever write.
If you want to master Graph traversals, this is the problem that unlocks the rest of them.
PS: Be honest. When you solve this, do you prefer DFS (Recursion) or BFS (Queue)? I’m Team DFS because I’m lazy and I hate managing manual Queues. Let’s argue in the comments. 👇
#LeetCode #SoftwareEngineering #CodingHumor #DataStructures #Algorithms #Python #TechLife #JobSearch
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: