reading-notes

Graphs Cheat Sheet

1. Terminology:

2. Representing Graphs:

3. Creating a Graph:

In JavaScript, we can represent a graph using an Object for the Adjacency List:

class Graph {
  constructor() {
    this.nodes = {};
  }

  addVertex(vertex) {
    if (!this.nodes[vertex]) this.nodes[vertex] = [];
  }

  addEdge(v1, v2) {
    this.nodes[v1].push(v2);
    this.nodes[v2].push(v1);
  }
}

4. Traversing Graphs:

// BFS
bfs(start) {
  const queue = [start];
  const visited = new Set(queue);

  while (queue.length) {
    const vertex = queue.shift();
    console.log(vertex);

    this.nodes[vertex].forEach(node => {
      if (!visited.has(node)) {
        queue.push(node);
        visited.add(node);
      }
    });
  }
}

// DFS
dfs(start, visited = new Set()) {
  console.log(start);
  visited.add(start);

  this.nodes[start].forEach(node => {
    if (!visited.has(node)) {
      this.dfs(node, visited);
    }
  });
}

5. Graph Algorithms: