LeetCode 547 Number of Provinces DFS Approach

🌞 Day 44 – LeetCode 75 ✅ 547. Number of Provinces Today’s problem was about finding how many connected components (provinces) exist in a graph represented using an adjacency matrix. Approach : I treated the matrix as a graph problem: - Each city = a node - isConnected[i][j] = 1 means there is a connection (edge) So the goal becomes: - Count how many disconnected groups exist. DFS Approach : - Maintain a visited[] array to track visited cities Loop through each city: - If not visited → it means a new province - Run DFS to mark all cities connected to it Complexity : - Time: O(n²) → because we scan adjacency matrix - Space: O(n) → visited array + recursion stack Key Insight : This is a classic Connected Components in Graph problem. Even though it looks like a matrix problem, it’s really: - How many disconnected graphs exist? Once you see that pattern, DFS/BFS becomes very natural. Restarting consistency again — building momentum one graph problem at a time 🚀 #LeetCode75 #Day44 #LeetCode #DSA #JavaScript #Graph #DFS #ConnectedComponents #ProblemSolving #Coding #LearningInPublic #Consistency

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories