Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c57d1be

Browse files
Merge pull request TheAlgorithms#571 from algobytewise/add-BreadthFirstSearch
add algorithm Breadth-first search
2 parents 4bc2b28 + 853386f commit c57d1be

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

‎Graphs/BreadthFirstSearch.js‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
Breadth-first search is an algorithm for traversing a graph. It's discovers all nodes reachable from the starting position by exploring all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.
3+
(description adapted from https://en.wikipedia.org/wiki/Breadth-first_search )
4+
(see also: https://www.koderdojo.com/blog/breadth-first-search-and-shortest-path-in-csharp-and-net-core )
5+
*/
6+
7+
/*
8+
Doctests
9+
> Array.from(breadthFirstSearch(graph, "C"))
10+
[ 'C', 'D', 'A', 'B', 'E' ]
11+
> Array.from(breadthFirstSearch(graph, "A"))
12+
[ 'A', 'B', 'D', 'E' ]
13+
> Array.from(breadthFirstSearch(graph, "F"))
14+
[ 'F', 'G' ]
15+
*/
16+
17+
function breadthFirstSearch (graph, startingNode) {
18+
// visited keeps track of all nodes visited
19+
const visited = new Set()
20+
21+
// queue contains the nodes to be explored in the future
22+
const queue = [startingNode]
23+
24+
while (queue.length > 0) {
25+
// start with the queue's first node
26+
const node = queue.shift()
27+
28+
if (!visited.has(node)) {
29+
// mark the node as visited
30+
visited.add(node)
31+
const neighbors = graph[node]
32+
33+
// put all its neighbors into the queue
34+
for (let i = 0; i < neighbors.length; i++) {
35+
queue.push(neighbors[i])
36+
}
37+
}
38+
}
39+
40+
return visited
41+
}
42+
43+
const graph = {
44+
A: ['B', 'D'],
45+
B: ['E'],
46+
C: ['D'],
47+
D: ['A'],
48+
E: ['D'],
49+
F: ['G'],
50+
G: []
51+
}
52+
/*
53+
A <-> B
54+
ʌ |
55+
| |
56+
v v
57+
C --> D <-- E
58+
59+
F --> G
60+
*/
61+
62+
console.log(breadthFirstSearch(graph, 'C'))
63+
console.log(breadthFirstSearch(graph, 'A'))
64+
console.log(breadthFirstSearch(graph, 'F'))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /