Skip to content

Commit e6f7ed5

Browse files
committed
chore: added bfs
1 parent 9304dc8 commit e6f7ed5

File tree

4 files changed

+155
-15
lines changed

4 files changed

+155
-15
lines changed

README.md

+46-15
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,18 @@
2828
- [Enqueue an element in Queue](#enqueue-an-element-in-queue)
2929
- [Dequeue an element from Queue](#dequeue-an-element-from-queue)
3030
- [Tree](#tree)
31-
- [Breadth-first Traversal (BFS)](#breadth-first-traversal-bfs)
32-
- [Depth-first Traversal (DFS)](#depth-first-traversal-dfs)
33-
- [DFS Vs BFS](#dfs-vs-bfs)
31+
- [Breadth-first Traversal (BFT)](#breadth-first-traversal-bft)
32+
- [Depth-first Traversal (DFT)](#depth-first-traversal-dft)
33+
- [Difference between Breadth-first vs Depth-first traversal](#difference-between-breadth-first-vs-depth-first-traversal)
3434
- [Binary Tree](#binary-tree)
3535
- [Binary Search Tree (BST)](#binary-search-tree-bst)
3636
- [Trie](#trie)
3737
- [Heap ( Priority Queue )](#heap--priority-queue-)
3838
- [Hash-Table](#hash-table)
3939
- [Graph](#graph)
40+
- [Implement Graph](#implement-graph)
41+
- [Breadth First Search](#breadth-first-search)
42+
- [Breadth First Search](#breadth-first-search-1)
4043
- [Algorithms Q&A](#algorithms-qa)
4144
- [Merge Sort](#merge-sort)
4245
- [Merge Sort Implementation](#merge-sort-implementation)
@@ -264,7 +267,9 @@ queue.shift(); // 4 , queue []
264267

265268
### Tree
266269

267-
A tree has hierarchical data and it has nodes.
270+
A tree has hierarchical data and it has nodes. It is a type of graph. Each node (except root) has exactly on parent and zero or more children.
271+
A tree is `acyclic` meaning it has no cycles: "a cycle is a path [AKA sequence] of edges and vertices wherein a vertex is reachable from itself".
272+
Therefore, a tree is also called as `Directed Acyclic Graph (DAG)`.
268273

269274
![](https://i.imgur.com/wUiUy0B.png)
270275

@@ -287,7 +292,7 @@ If you want to store hierarchical data use Tree.
287292

288293
You should know about `Binary Tree` and `Binary Search Tree`.
289294

290-
#### Breadth-first Traversal (BFS)
295+
#### Breadth-first Traversal (BFT)
291296

292297
In BFS algorithm, a graph is traversed in layer-by-layer fashion. point. The queue is used to implement BFS.
293298

@@ -298,13 +303,14 @@ Example: Suppose you have given a tree structure and asked to calculate the aver
298303
- **Strategy**: `Iterative`
299304
- **Time Complexity**: `O(n logn)`
300305
- **Space Complexity**: `O(n logn)`
306+
- Use `Queue` while coding.
301307

302308
![](https://i.imgur.com/DdFyXGx.png)
303309

304310
- [Breadth-first Traversal Exercise](https://codepen.io/roopkt/pen/bGqjVZe?editors=0010)
305311
- [Breadth-first Traversal Answer](https://codepen.io/roopkt/pen/XWMBdWv?editors=0010)
306312

307-
#### Depth-first Traversal (DFS)
313+
#### Depth-first Traversal (DFT)
308314

309315
The DFS algorithm we start from starting point and go into depth of graph until we reach a dead end and then move up to parent node (Backtrack). The stack is used to implement DFS.
310316

@@ -313,21 +319,22 @@ The DFS algorithm we start from starting point and go into depth of graph until
313319
- **Strategy**: `Recursive`
314320
- **Time Complexity**: `O(n logn)`
315321
- **Space Complexity**: `O(n logn)`
322+
- Use `Stack` while coding.
316323

317324
![](https://i.imgur.com/DdFyXGx.png)
318325

319326
- [Breadth-first Traversal Exercise](https://codepen.io/roopkt/pen/bGqjVZe?editors=0010)
320327
- [Breadth-first Traversal Answer](https://codepen.io/roopkt/pen/XWMBdWv?editors=0010)
321328

322-
#### DFS Vs BFS
329+
#### Difference between Breadth-first vs Depth-first traversal
323330

324-
| DFS | BFS |
325-
| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
326-
| Search from root to the leaf | Search level by level |
327-
| Uses Stack to sort | Uses Queue to sort |
328-
| Time complexity: Fast | Time complexity: Slow |
329-
| Where to use: if you can find at root or leaf, find connected components. | Where to use: Find shortest path,find connected components. When you think you have less data go for it. |
330-
| Time Complexity: O(V+E) | Time Complexity: O(V+E) |
331+
| BFS | DFS |
332+
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
333+
| Search level by level | Search from root to the leaf |
334+
| Uses Queue to sort | Uses Stack to sort |
335+
| Time complexity: Slow | Time complexity: Fast |
336+
| Where to use: solution is not far from the root of the tree,If the tree is very deep and solutions are rare, If solutions are frequent but located deep in the tree, | Where to use: tree is very wide |
337+
| Time Complexity: O(V+E) | Time Complexity: O(V+E) |
331338

332339
### Binary Tree
333340

@@ -385,7 +392,31 @@ It is just like a dictionary or key value pair.
385392
![](https://i.imgur.com/kYlxMWJ.png)
386393

387394
Graph represents network. It has Nodes, Vertices and Edges.
388-
|
395+
396+
#### Implement Graph
397+
398+
![](https://i.imgur.com/eqzKDIV.png)
399+
400+
[Exercise](https://codepen.io/roopkt/pen/ZEejLJe?editors=0010)
401+
[Answer](https://codepen.io/roopkt/pen/vYxagrP?editors=0010)
402+
403+
#### Breadth First Search
404+
405+
When you want to find all possible routes between airports then you want to use BFS.
406+
Find all possible routes from `PHX` to `BKK`. Also then you can decide which path is the shortest one.
407+
408+
![](https://i.imgur.com/CvPhRQx.png)
409+
410+
[Breadth First Search Find all possible routes Exercise & Answer](./src/data-structure/5-graph/breadth-first-search.mjs)
411+
412+
#### Breadth First Search
413+
414+
When you want to find all possible routes between airports then you want to use this.
415+
Find all possible routes from `PHX` to `BKK`
416+
417+
![](https://i.imgur.com/CvPhRQx.png)
418+
419+
[Breadth First Search Exercise Answer](./src/data-structure/5-graph/breadth-first-search.mjs)
389420

390421
## Algorithms Q&A
391422

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* Search all possible routes from PHX and BKK
3+
* @param start node
4+
*/
5+
6+
import { createGraph } from './implement-graph.mjs';
7+
8+
function bfs(graph, start, end) {
9+
const queue = [];
10+
queue.push(start);
11+
const visited = new Set();
12+
13+
while (queue.length) {
14+
var origin = queue.shift();
15+
16+
const destinations = graph.nodes.get(origin);
17+
18+
if (!destinations) continue;
19+
20+
for (const destination of destinations) {
21+
if (end === destination) {
22+
console.log(`====We found Bangkok====`);
23+
}
24+
25+
if (!visited.has(destination)) {
26+
queue.push(destination);
27+
visited.add(destination);
28+
console.log(`Destination: ${destination}`);
29+
}
30+
}
31+
}
32+
}
33+
34+
const graph = createGraph();
35+
bfs(graph, 'PHX', 'BKK');
36+
37+
/**
38+
* PHX => [ ABC, XYZ ]
39+
* ABC => [ BBB, CCC ]
40+
*
41+
* CCC => [ BKK, DDD ]
42+
*
43+
* s =[ ]
44+
* o = phx
45+
* a =[abc,xyz]
46+
*
47+
* s =[ xyz , bbb,ccc]
48+
* o = abc
49+
* a= [bbb,ccc]
50+
*
51+
* s =[ bbb,ccc]
52+
* o = xyz
53+
* a= null
54+
*
55+
*
56+
* s =[ccc]
57+
* o = bbb
58+
* a= null
59+
*
60+
* s =[ccc]
61+
* o = ccc
62+
* a= [bkk, ddd]
63+
* we found bkk
64+
*/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
export class Graph {
2+
constructor() {
3+
this.nodes = new Map();
4+
}
5+
6+
addNode(value) {
7+
this.nodes.set(value, []);
8+
}
9+
10+
addEdge(origin, destination) {
11+
this.nodes.has(origin)
12+
? this.nodes.get(origin).push(destination)
13+
: this.nodes.set(origin, [destination]);
14+
15+
this.nodes.has(destination)
16+
? this.nodes.get(destination).push(origin)
17+
: this.nodes.set(destination, [origin]);
18+
}
19+
}
20+
21+
export const routes = [
22+
['PHX', 'LAX'],
23+
['PHX', 'JFK'],
24+
['JFK', 'OKC'],
25+
['JFK', 'HEL'],
26+
['JFK', 'LOS'],
27+
['MEX', 'LAX'],
28+
['MEX', 'BKK'],
29+
['MEX', 'LIM'],
30+
['MEX', 'EZE'],
31+
['LIM', 'BKK'],
32+
];
33+
34+
export function createGraph(edges = routes) {
35+
const graph = new Graph();
36+
edges.forEach((route) => {
37+
graph.addEdge(...route);
38+
});
39+
40+
return graph;
41+
}
42+
43+
const graph = createGraph(routes);
44+
45+
console.log(graph);

0 commit comments

Comments
 (0)