> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/union-find/547.-number-of-provinces.md).

# 547. Number of Provinces

![](/files/-MaatmJQKJtlwhlPWrJM)

![](/files/-Maatr6ccQn8k-CjWZ6i)

~~time: O(edges\*nodes)  => 我想應該不是~~

~~t~~

space: O(n)

![](/files/-MikFYSq_uey2et9J7Bz)

因為有環(has same root)就**不能構成一個邊**,&#x20;

所以無環(x !=y)時, 可以成立一個邊, 也就會少掉一個 circle num

當 isConnected\[i]\[j] == 1 => 去找是不是對應也是1 \[j]\[i]  也就是利用 union find => 如果沒有circe => 代表有邊 .=> 代表是同一個group => res--&#x20;

```java
class Solution {
    public int findCircleNum(int[][] isConnected) {
        // use union find
        int n = isConnected.length;
            
        int res = n;
        int roots[] = new int[n];
        for (int i = 0; i < n; i++) {
            roots[i] = -1;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < isConnected[0].length; j++) {
                if (isConnected[i][j] == 1) {
                    int x = find(roots, i);
                    int y = find(roots, j);
                    if (x != y) {
                        roots[x] = y;
                        res--;
                    }
                }
                
            }
        }
        return res;
    }
    private int find(int[] roots, int i) {
        while (roots[i] != -1) {
            i = roots[i];
        }
        return i;
    }
}
```

### with path compression

```java
class Solution {
    public int findCircleNum(int[][] isConnected) {
        // use union find
        // so 0,0 is not
        if (isConnected == null || isConnected.length == 0) return 0;
        int res = isConnected.length;
        int n = isConnected.length;
        
        int[] roots = new int[n];
        for (int i = 0; i < n; i++) {
            roots[i] = i;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (isConnected[i][j] == 1) {
                    res = union(roots, i, j, res);
                }
            } 
        }
        return res;
    }
    
    private int union(int roots[], int i , int j, int res) {
        int x = find(roots, i);
        int y = find(roots, j);
        if (x != y) {
            roots[x] = y;
            res--;
        }
        return res;
    }

    private int find(int roots[], int i) {
        while (roots[i] != i) {
            roots[i] = roots[roots[i]]; // add path compression
            i = roots[i];
        }
        return i;
    }
}
```

## use Class

```java
class Solution {
    public int findCircleNum(int[][] isConnected) {
        
        int n = isConnected.length;
        DSU dsu = new DSU(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (isConnected[i][j] == 1) {
                    dsu.union(i, j);
                }
            }
        }
        return dsu.res;
    }
    
    class DSU {
        int roots[];
        int res;
        
        DSU(int n) {
            roots = new int[n];
            res = n;
            for (int i = 0 ; i < n; i++) {
                roots[i] = i;
            }
        }
        
        private void union(int i, int j) {
            int x = find(i);
            int y = find(j);
            if (x != y) {
                roots[x] = y;
                res--;
            }
            
        }
        
        private int find(int x) {
            if (roots[x] != x) {
                roots[x] = find(roots[x]);
            }
            return roots[x];
        }
    }
}
```

## Solution 2: DFS

```java
class Solution {
    public int findCircleNum(int[][] isConnected) {

        int[] visited = new int[isConnected.length]; // dont need init to 0
        int count = 0;
        for (int i = 0; i < isConnected.length; i++) {
            if (visited[i] == 0) {
                dfs(isConnected, visited, i);
                count++;
            }
        }
        return count;
    }

    public void dfs(int[][] isConnected, int[] visited, int i) {
        for (int j = 0; j < isConnected.length; j++) {
            if (isConnected[i][j] == 1 && visited[j] == 0) {
                visited[j] = 1;
                dfs(isConnected, visited, j);
            }
        }
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://timmybeeflin.gitbook.io/cracking-leetcode/union-find/547.-number-of-provinces.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.
