LeetCode 547: Number of Provinces Solution

Master LeetCode problem 547 (Number of Provinces), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

To solve this problem, we can use a depth-first search (DFS) algorithm to traverse the graph of cities and find all connected provinces. We will maintain a boolean array to mark visited cities and increment the count of provinces whenever we encounter a new unvisited city during the DFS traversal.

  • Algorithm:

    1. Initialize a boolean array visited of size n to keep track of visited cities.
    2. Iterate through each city, and if a city is not visited, perform a DFS traversal starting from that city.
    3. In the DFS function, mark the current city as visited and recursively call the DFS function on its connected cities.
    4. Increment the province count whenever a new unvisited city is encountered in the DFS traversal.
    5. Return the total count of provinces.
  • Time Complexity: O(n^2) where n is the number of cities.

  • Space Complexity: O(n) for the boolean array and recursion stack.

:

Solution Code

class Solution {
    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        boolean[] visited = new boolean[n];
        int provinces = 0;
        
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                dfs(isConnected, visited, i);
                provinces++;
            }
        }
        
        return provinces;
    }
    
    private void dfs(int[][] isConnected, boolean[] visited, int city) {
        visited[city] = true;
        
        for (int j = 0; j < isConnected.length; j++) {
            if (isConnected[city][j] == 1 && !visited[j]) {
                dfs(isConnected, visited, j);
            }
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 547 (Number of Provinces)?

This page provides optimized solutions for LeetCode problem 547 (Number of Provinces) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 547 (Number of Provinces)?

The time complexity for LeetCode 547 (Number of Provinces) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 547 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 547 in Java, C++, or Python.

Back to LeetCode Solutions