# CODE

```python
class Solution:
    def findCircleNum(self, isConnected: List[List[int]]) -> int:
        num_province = len(isConnected)
        # Array that stores the parent of a given node, initially
        # every node's parent is set itself
        ancestor = [i for i in range(num_province)]
        # Rank for each node
        rank = [1 for _ in range(num_province)]
        
        def find_ancestor(node):
            # While we dont reach to top most ancestor
            while node != ancestor[node]:
                # Path compression, for a give node, its grandparent is
                # is also a parent (ancestor) hence reduce the hop from 
                # child -> parent -> grandparent
                ancestor[node] = ancestor[ancestor[node]]
                # For the parent find its parent in the next iteration
                node = ancestor[node]
            # Should be the top most ancestor
            return node
                
        def union(node1, node2):
            node1_ancestor, node2_ancestor = find_ancestor(node1), find_ancestor(node2)
            # Both nodes have common ancestor, no need to union them
            if node1_ancestor == node2_ancestor:
                return 0
            
            # If node1 ancestor is elder (rank), ask node2 to merge into it
            # also, with the merge node1 ancestor is more elder now
            if rank[node1_ancestor] > rank[node2_ancestor]:
                ancestor[node2_ancestor] = node1_ancestor
                rank[node1_ancestor] += rank[node2_ancestor]
            else:
                ancestor[node1_ancestor] = node2_ancestor
                rank[node2_ancestor] += rank[node1_ancestor]
            return 1
                
        for node1 in range(len(isConnected)):
            for node2 in range(len(isConnected[0])):
                if isConnected[node1][node2] == 1:
                    num_province -= union(node1, node2)
        return num_province
        
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chiragjain.gitbook.io/neetcode/547-number-of-provinces/code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
