diff --git a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README.md b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README.md index 99abe76a1f440..f4548a7fcff71 100644 --- a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README.md +++ b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README.md @@ -492,4 +492,47 @@ function countComponents(n: number, edges: number[][]): number { + + +### 方法 3: BFS + + + +#### TypeScript + +```ts +function countComponents(n: number, edges: number[][]): number { + const g: number[][] = Array.from({ length: n }, () => []); + const vis = new Set(); + let ans = 0; + + for (const [i, j] of edges) { + g[i].push(j); + g[j].push(i); + } + + const dfs = (i: number) => { + if (vis.has(i)) return; + + vis.add(i); + for (const j of g[i]) { + dfs(j); + } + }; + + for (let i = 0; i < n; i++) { + if (vis.has(i)) continue; + + dfs(i); + ans++; + } + + return ans; +} +``` + + + + + diff --git a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md index ff24fe2827192..973a9e031a081 100644 --- a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md +++ b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md @@ -487,4 +487,47 @@ function countComponents(n: number, edges: number[][]): number { + + +### Solution 3: BFS + + + +#### TypeScript + +```ts +function countComponents(n: number, edges: number[][]): number { + const g: number[][] = Array.from({ length: n }, () => []); + const vis = new Set(); + let ans = 0; + + for (const [i, j] of edges) { + g[i].push(j); + g[j].push(i); + } + + const dfs = (i: number) => { + if (vis.has(i)) return; + + vis.add(i); + for (const j of g[i]) { + dfs(j); + } + }; + + for (let i = 0; i < n; i++) { + if (vis.has(i)) continue; + + dfs(i); + ans++; + } + + return ans; +} +``` + + + + + diff --git a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/Solution3.ts b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/Solution3.ts new file mode 100644 index 0000000000000..18a3afec2fd52 --- /dev/null +++ b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/Solution3.ts @@ -0,0 +1,28 @@ +function countComponents(n: number, edges: number[][]): number { + const g: number[][] = Array.from({ length: n }, () => []); + const vis = new Set(); + let ans = 0; + + for (const [i, j] of edges) { + g[i].push(j); + g[j].push(i); + } + + const dfs = (i: number) => { + if (vis.has(i)) return; + + vis.add(i); + for (const j of g[i]) { + dfs(j); + } + }; + + for (let i = 0; i < n; i++) { + if (vis.has(i)) continue; + + dfs(i); + ans++; + } + + return ans; +}