Before algorithms, understand these terms:
| Term | Meaning |
|---|---|
| Vertex (Node) | A point in a graph |
| Edge | A connection between two nodes |
| Directed Graph | Edge has a direction (A âž” B) |
| Undirected Graph | Edge has no direction (A — B) |
| Weighted Graph | Each edge has a weight (cost) |
| Adjacency List | Store neighbors for each node |
| Adjacency Matrix | 2D array where matrix[i][j] = 1 if edge exists |
1. Push starting node into queue.
2. While queue is not empty:
- extract
- proceess node
- Push neighbours into the queue
3. manage visited nodes
âž¡ Use cases: Shortest path in unweighted graphs, Level Order Traversal
Template
function bfs(graph, src) {
let q =[src]
let visited = new Set()
while(q.length) {
// extract
let currentNode = q.shift()
if(visited.has(currentNode)) continue
//process
console.log(currentNode)
//visit neighbours
for(let neighbour of graph[currentNode]){
q.push(neighbour)
}
}
}
// Driver code ------
let inputGraph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D", "E"],
"D": ["B", "C"],
"E": ["C"]
}
dfs(inputGraph, "A")
1. Start from a node.
2. Visit it and mark visited.
3. For each unvisited neighbor:
- Recurse/Push into stack
âž¡ Use cases: Cycle Detection, Connected Components
Template
function dfs(graph, node, visited = new Set()) {
if(!node) return
//process node
console.log(node)
visited.add(node)
for(let neighbour of graph[node]) {
dfs(graph, neighbour, visited)
}
}
// Driver code ------
let inputGraph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D", "E"],
"D": ["B", "C"],
"E": ["C"]
}
dfs(inputGraph, "A")