Detecting Cycles in 2D Grid with DFS

🚀 Day 245 of #500DaysOfCode Solved LeetCode 1559 – Detect Cycles in 2D Grid 🔄 💡 Approach: Traverse the grid using DFS Maintain a visited matrix While exploring neighbors: Move only in 4 directions (up, down, left, right) Only continue if the character matches Track parent cell (px, py) to avoid false cycle detection If we reach a visited cell that is not the parent → cycle found ✅ ⚡ Key Insight: Classic cycle detection in an undirected graph Parent tracking is crucial to avoid revisiting immediate previous node ⏱️ Complexity: Time: O(m × n) Space: O(m × n) (visited + recursion stack) ✨ Takeaway: Grid problems often map to graph traversal → think DFS/BFS + cycle detection patterns. Day 245 ✅ Still consistent 💪🔥 #LeetCode #DSA #DFS #Graphs #GridProblems #Consistency

  • text

To view or add a comment, sign in

Explore content categories