تخيل إنك في متاهة وعايز تزور كل الغرف:
نزور كل node في الـ graph مرة واحدة بس!
مهم نتتبع الـ nodes اللي زرناها عشان ما نلفش في حلقة!
Breadth-First Search - البحث بالعرض
📦 بيستخدم Queue (FIFO)
First In, First Out - اللي يدخل الأول يخرج الأول
بيزور level by level
Depth-First Search - البحث بالعمق
📚 بيستخدم Stack (LIFO)
Last In, First Out - اللي يدخل الأخير يخرج الأول
أو ممكن نستخدم Recursion!
بينزل للعمق الأول، بعدين يرجع
Queue (BFS)
Stack (DFS)
Click "BFS" or "DFS" to start.
| المقارنة | BFS | DFS |
|---|---|---|
| Data Structure | Queue | Stack / Recursion |
| Time | O(V + E) | O(V + E) |
| Space | O(V) | O(V) |
| Shortest Path? | ✓ Yes | ✗ No |
| الأفضل لـ | Shortest path, Level-order | Cycle detection, Topological sort |
function bfs(graph, start) {
const visited = new Set();
const queue = [start];
visited.add(start);
while (queue.length > 0) {
const node = queue.shift();
console.log(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
}
function dfs(graph, start) {
const visited = new Set();
const stack = [start];
while (stack.length > 0) {
const node = stack.pop();
if (visited.has(node)) continue;
visited.add(node);
console.log(node);
for (const neighbor of graph[node]) {
stack.push(neighbor);
}
}
}