Detecting Cycles in 2D Grid with Java DFS

🚀 Solved “Detect Cycles in 2D Grid” (LeetCode 1559) Worked on a classic graph problem and implemented an efficient DFS-based solution in Java. 🔍 Key idea: Treat the grid as an undirected graph and detect cycles by: Traversing only same-character neighbors Tracking the parent cell to avoid false cycles Identifying a cycle when visiting an already visited node (not parent) ⚡ Insight: Using a recursion stack (like in directed graphs) gives wrong results here — parent tracking is the correct approach. ⏱ Complexity: Time: O(m × n) Space: O(m × n) 📌 Also added a clean, documented version to my GitHub with test cases. 🔗 LeetCode: https://lnkd.in/d6CKa-BN 🔗 GitHub: https://lnkd.in/gnEfmGAg #Java #DSA #GraphAlgorithms #LeetCode #CodingJourney

  • text

To view or add a comment, sign in

Explore content categories