feat: 关于图第1971题js代码

This commit is contained in:
dengyongchi
2024-01-06 10:56:02 +08:00
parent 4b0226cf2c
commit 30af534ee9

View File

@ -14,20 +14,18 @@
给你数组 edges 和整数 n、start 和 end如果从 start 到 end 存在 有效路径 ,则返回 true否则返回 false 。
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20220705101442.png)
提示:
* 1 <= n <= 2 * 10^5
* 0 <= edges.length <= 2 * 10^5
* edges[i].length == 2
* 0 <= ui, vi <= n - 1
* ui != vi
* 0 <= start, end <= n - 1
* 不存在双向边
* 不存在指向顶点自身的边
- 1 <= n <= 2 \* 10^5
- 0 <= edges.length <= 2 \* 10^5
- edges[i].length == 2
- 0 <= ui, vi <= n - 1
- ui != vi
- 0 <= start, end <= n - 1
- 不存在双向边
- 不存在指向顶点自身的边
## 思路
@ -70,7 +68,7 @@ void join(int u, int v) {
}
```
以上模板中,只要修改 n 大小就可以,本题n不会超过2 * 10^5。
以上模板中,只要修改 n 大小就可以,本题 n 不会超过 2 \* 10^5。
并查集主要有三个功能。
@ -206,6 +204,85 @@ class Solution:
return find(source) == find(destination)
```
### Javascript
Javascript 并查集解法如下:
```Javascript
class unionF{
constructor(n){
this.count = n
this.roots = new Array(n).fill(0).map((item,index)=>index)
}
findRoot(x){
if(this.roots[x]!==x){
this.roots[x] = this.findRoot(this.roots[x])
}
return this.roots[x]
}
union(x,y){
const rx = this.findRoot(x)
const ry = this.findRoot(y)
this.roots[rx] = ry
this.count--
}
isConnected(x,y){
return this.findRoot(x)===this.findRoot(y)
}
}
var validPath = function(n, edges, source, destination) {
const UF = new unionF(n)
for(const [s,t] of edges){
UF.union(s,t)
}
return UF.isConnected(source,destination)
};
```
Javascript 双向 bfs 解法如下:
```Javascript
var validPath = function(n, edges, source, destination) {
const graph = new Array(n).fill(0).map(()=>[])
for(const [s,t] of edges){
graph[s].push(t)
graph[t].push(s)
}
const visited = new Array(n).fill(false)
function bfs(start,end,graph){
const startq = [start]
const endq = [end]
while(startq.length&&endq.length){
const slen = startq.length
for(let i = 0;i<slen;i++){
const scur = startq.shift()
if(visited[scur]) continue
if(endq.includes(scur)) return true
visited[scur] = true
const neighbors = graph[scur]
startq.push(...neighbors)
}
const elen = endq.length
for(let i = 0;i<elen;i++){
const ecur = endq.shift()
if(visited[ecur]) continue
if(startq.includes(ecur)) return true
visited[ecur] = true
const neighbors = graph[ecur]
endq.push(...neighbors)
}
}
return false
}
return bfs(source,destination,graph)
};
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">