Skip to content

Commit a88702e

Browse files
committed
feat(js): add modular solution and documentation for normal challenge 5 - BFS and DFS Graph Traversal
1 parent 15a2096 commit a88702e

File tree

3 files changed

+387
-0
lines changed

3 files changed

+387
-0
lines changed
Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Implement breadth-first search (BFS) and depth-first search (DFS) algorithms to traverse a graph represented by adjacency lists. Ensure coverage of both connected and disconnected graphs.
7+
8+
### Code Explanation
9+
The `Graph` class represents an undirected graph using adjacency lists. It supports:
10+
- `addEdge(u, v)`: Adds an undirected edge between vertices `u` and `v`.
11+
- `bfs(start)`: Performs BFS traversal starting from a given vertex.
12+
- `dfs(start)`: Performs DFS traversal starting from a given vertex.
13+
- `bfsDisconnected()`: Performs BFS traversal covering all vertices, including disconnected components.
14+
- `dfsDisconnected()`: Performs DFS traversal covering all vertices, including disconnected components.
15+
16+
### Relevant Code Snippet
17+
18+
```javascript
19+
class Graph {
20+
constructor(vertices) {
21+
this.V = vertices;
22+
this.adj = Array.from({ length: vertices }, () => []);
23+
}
24+
25+
addEdge(u, v) {
26+
this.adj[u].push(v);
27+
this.adj[v].push(u); // Undirected graph
28+
}
29+
30+
bfs(start) {
31+
const visited = new Array(this.V).fill(false);
32+
const queue = [];
33+
const result = [];
34+
35+
visited[start] = true;
36+
queue.push(start);
37+
38+
while (queue.length > 0) {
39+
const vertex = queue.shift();
40+
result.push(vertex);
41+
42+
for (const neighbor of this.adj[vertex]) {
43+
if (!visited[neighbor]) {
44+
visited[neighbor] = true;
45+
queue.push(neighbor);
46+
}
47+
}
48+
}
49+
return result;
50+
}
51+
52+
dfsUtil(v, visited, result) {
53+
visited[v] = true;
54+
result.push(v);
55+
56+
for (const neighbor of this.adj[v]) {
57+
if (!visited[neighbor]) {
58+
this.dfsUtil(neighbor, visited, result);
59+
}
60+
}
61+
}
62+
63+
dfs(start) {
64+
const visited = new Array(this.V).fill(false);
65+
const result = [];
66+
this.dfsUtil(start, visited, result);
67+
return result;
68+
}
69+
70+
bfsDisconnected() {
71+
const visited = new Array(this.V).fill(false);
72+
const result = [];
73+
74+
for (let i = 0; i < this.V; i++) {
75+
if (!visited[i]) {
76+
const queue = [];
77+
visited[i] = true;
78+
queue.push(i);
79+
80+
while (queue.length > 0) {
81+
const vertex = queue.shift();
82+
result.push(vertex);
83+
84+
for (const neighbor of this.adj[vertex]) {
85+
if (!visited[neighbor]) {
86+
visited[neighbor] = true;
87+
queue.push(neighbor);
88+
}
89+
}
90+
}
91+
}
92+
}
93+
return result;
94+
}
95+
96+
dfsDisconnected() {
97+
const visited = new Array(this.V).fill(false);
98+
const result = [];
99+
100+
for (let i = 0; i < this.V; i++) {
101+
if (!visited[i]) {
102+
this.dfsUtil(i, visited, result);
103+
}
104+
}
105+
return result;
106+
}
107+
}
108+
```
109+
110+
### Example Usage
111+
112+
```javascript
113+
import Graph from './graph.js';
114+
115+
const g = new Graph(7);
116+
const edges = [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [5, 6]];
117+
for (const [u, v] of edges) {
118+
g.addEdge(u, v);
119+
}
120+
121+
console.log('BFS starting from vertex 0:');
122+
console.log(g.bfs(0));
123+
124+
console.log('DFS starting from vertex 0:');
125+
console.log(g.dfs(0));
126+
127+
console.log('BFS for disconnected graph:');
128+
console.log(g.bfsDisconnected());
129+
130+
console.log('DFS for disconnected graph:');
131+
console.log(g.dfsDisconnected());
132+
```
133+
134+
---
135+
136+
## Versión en Español
137+
138+
### Descripción del Reto
139+
Implementa los algoritmos de búsqueda en anchura (BFS) y búsqueda en profundidad (DFS) para recorrer un grafo representado por listas de adyacencia. Asegura la cobertura de grafos conectados y desconectados.
140+
141+
### Explicación del Código
142+
La clase `Graph` representa un grafo no dirigido usando listas de adyacencia. Soporta:
143+
- `addEdge(u, v)`: Añade una arista no dirigida entre los vértices `u` y `v`.
144+
- `bfs(start)`: Realiza un recorrido BFS comenzando desde un vértice dado.
145+
- `dfs(start)`: Realiza un recorrido DFS comenzando desde un vértice dado.
146+
- `bfsDisconnected()`: Realiza un recorrido BFS cubriendo todos los vértices, incluyendo componentes desconectados.
147+
- `dfsDisconnected()`: Realiza un recorrido DFS cubriendo todos los vértices, incluyendo componentes desconectados.
148+
149+
### Fragmento de Código Relevante
150+
151+
```javascript
152+
class Graph {
153+
constructor(vertices) {
154+
this.V = vertices;
155+
this.adj = Array.from({ length: vertices }, () => []);
156+
}
157+
158+
addEdge(u, v) {
159+
this.adj[u].push(v);
160+
this.adj[v].push(u); // Grafo no dirigido
161+
}
162+
163+
bfs(start) {
164+
const visited = new Array(this.V).fill(false);
165+
const queue = [];
166+
const result = [];
167+
168+
visited[start] = true;
169+
queue.push(start);
170+
171+
while (queue.length > 0) {
172+
const vertex = queue.shift();
173+
result.push(vertex);
174+
175+
for (const neighbor of this.adj[vertex]) {
176+
if (!visited[neighbor]) {
177+
visited[neighbor] = true;
178+
queue.push(neighbor);
179+
}
180+
}
181+
}
182+
return result;
183+
}
184+
185+
dfsUtil(v, visited, result) {
186+
visited[v] = true;
187+
result.push(v);
188+
189+
for (const neighbor of this.adj[v]) {
190+
if (!visited[neighbor]) {
191+
this.dfsUtil(neighbor, visited, result);
192+
}
193+
}
194+
}
195+
196+
dfs(start) {
197+
const visited = new Array(this.V).fill(false);
198+
const result = [];
199+
this.dfsUtil(start, visited, result);
200+
return result;
201+
}
202+
203+
bfsDisconnected() {
204+
const visited = new Array(this.V).fill(false);
205+
const result = [];
206+
207+
for (let i = 0; i < this.V; i++) {
208+
if (!visited[i]) {
209+
const queue = [];
210+
visited[i] = true;
211+
queue.push(i);
212+
213+
while (queue.length > 0) {
214+
const vertex = queue.shift();
215+
result.push(vertex);
216+
217+
for (const neighbor of this.adj[vertex]) {
218+
if (!visited[neighbor]) {
219+
visited[neighbor] = true;
220+
queue.push(neighbor);
221+
}
222+
}
223+
}
224+
}
225+
}
226+
return result;
227+
}
228+
229+
dfsDisconnected() {
230+
const visited = new Array(this.V).fill(false);
231+
const result = [];
232+
233+
for (let i = 0; i < this.V; i++) {
234+
if (!visited[i]) {
235+
this.dfsUtil(i, visited, result);
236+
}
237+
}
238+
return result;
239+
}
240+
}
241+
```
242+
243+
### Ejemplo de Uso
244+
245+
```javascript
246+
import Graph from './graph.js';
247+
248+
const g = new Graph(7);
249+
const edges = [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [5, 6]];
250+
for (const [u, v] of edges) {
251+
g.addEdge(u, v);
252+
}
253+
254+
console.log('BFS starting from vertex 0:');
255+
console.log(g.bfs(0));
256+
257+
console.log('DFS starting from vertex 0:');
258+
console.log(g.dfs(0));
259+
260+
console.log('BFS for disconnected graph:');
261+
console.log(g.bfsDisconnected());
262+
263+
console.log('DFS for disconnected graph:');
264+
console.log(g.dfsDisconnected());
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
// graph.js - Graph class with BFS and DFS traversals
2+
3+
class Graph {
4+
constructor(vertices) {
5+
this.V = vertices;
6+
this.adj = Array.from({ length: vertices }, () => []);
7+
}
8+
9+
addEdge(u, v) {
10+
this.adj[u].push(v);
11+
this.adj[v].push(u); // Undirected graph
12+
}
13+
14+
bfs(start) {
15+
const visited = new Array(this.V).fill(false);
16+
const queue = [];
17+
const result = [];
18+
19+
visited[start] = true;
20+
queue.push(start);
21+
22+
while (queue.length > 0) {
23+
const vertex = queue.shift();
24+
result.push(vertex);
25+
26+
for (const neighbor of this.adj[vertex]) {
27+
if (!visited[neighbor]) {
28+
visited[neighbor] = true;
29+
queue.push(neighbor);
30+
}
31+
}
32+
}
33+
return result;
34+
}
35+
36+
dfsUtil(v, visited, result) {
37+
visited[v] = true;
38+
result.push(v);
39+
40+
for (const neighbor of this.adj[v]) {
41+
if (!visited[neighbor]) {
42+
this.dfsUtil(neighbor, visited, result);
43+
}
44+
}
45+
}
46+
47+
dfs(start) {
48+
const visited = new Array(this.V).fill(false);
49+
const result = [];
50+
this.dfsUtil(start, visited, result);
51+
return result;
52+
}
53+
54+
bfsDisconnected() {
55+
const visited = new Array(this.V).fill(false);
56+
const result = [];
57+
58+
for (let i = 0; i < this.V; i++) {
59+
if (!visited[i]) {
60+
const queue = [];
61+
visited[i] = true;
62+
queue.push(i);
63+
64+
while (queue.length > 0) {
65+
const vertex = queue.shift();
66+
result.push(vertex);
67+
68+
for (const neighbor of this.adj[vertex]) {
69+
if (!visited[neighbor]) {
70+
visited[neighbor] = true;
71+
queue.push(neighbor);
72+
}
73+
}
74+
}
75+
}
76+
}
77+
return result;
78+
}
79+
80+
dfsDisconnected() {
81+
const visited = new Array(this.V).fill(false);
82+
const result = [];
83+
84+
for (let i = 0; i < this.V; i++) {
85+
if (!visited[i]) {
86+
this.dfsUtil(i, visited, result);
87+
}
88+
}
89+
return result;
90+
}
91+
}
92+
93+
export default Graph;
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// main.js - Example usage of Graph with BFS and DFS traversals
2+
3+
import Graph from './graph.js';
4+
5+
/*
6+
Challenge: Implement breadth-first search (BFS) and depth-first search (DFS) algorithms to traverse a graph represented by adjacency lists.
7+
Ensure coverage of both connected and disconnected graphs.
8+
*/
9+
10+
function main() {
11+
const g = new Graph(7);
12+
const edges = [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5], [5, 6]];
13+
for (const [u, v] of edges) {
14+
g.addEdge(u, v);
15+
}
16+
17+
console.log('BFS starting from vertex 0:');
18+
console.log(g.bfs(0));
19+
20+
console.log('DFS starting from vertex 0:');
21+
console.log(g.dfs(0));
22+
23+
console.log('BFS for disconnected graph:');
24+
console.log(g.bfsDisconnected());
25+
26+
console.log('DFS for disconnected graph:');
27+
console.log(g.dfsDisconnected());
28+
}
29+
30+
main();

0 commit comments

Comments
 (0)