-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_182.js
73 lines (58 loc) Β· 1.4 KB
/
problem_182.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import Graph from './data-structures/Graph';
/**
* Check if an undirected graph is minimally connected
* i.e - removal of one edge make it disconnected
* Time Complexity: O(|V| + |E|)
* @param {Graph} graph
* @return {boolean}
*/
function isMinimallyConnected(graph) {
// base case
if (graph.nodes.length <= 0) return false;
const queue = [];
const explored = [];
queue.push(graph.nodes[0]);
explored.push(graph.nodes[0]);
// run BFS from starting node
while (queue.length !== 0) {
const temp = queue.shift();
// check that any node doesn't have a single path
if (graph.edges[temp].length <= 1) return false;
// check unexmplored nodes
graph.edges[temp]
.filter(n => !explored.includes(n.node))
.forEach(n => {
explored.push(n.node);
queue.push(n.node);
});
}
return true;
}
const graph = new Graph();
graph.addNode('a');
graph.addNode('b');
graph.addNode('c');
graph.addNode('d');
graph.addNode('e');
graph.addEdge('a', 'b');
graph.addEdge('a', 'c');
graph.addEdge('d', 'b');
graph.addEdge('d', 'c');
graph.addEdge('d', 'e');
/**
* a ------ b
* | |
* | |
* | |
* c ------ d --- e
*/
console.log(isMinimallyConnected(graph)); // false
graph.addEdge('e', 'b');
/**
* a ------- b
* | | \
* | | \
* | | \
* c ------ d --- e
*/
console.log(isMinimallyConnected(graph)); // true