Several common graph algorithms in JS

Here are JavaScript examples of some common graph algorithms:

1. Breadth First Search (Breadth First Search, BFS):

function BFS(graph, start) {
  const visited = new Set();
  const queue = [start];

  while (queue.length > 0) {
    const vertex = queue.shift();
    visited.add(vertex);
    console.log(vertex);
    const neighbors = graph[vertex];
    for (const neighbor of neighbors) {
      if (!visited.has(neighbor)) {
        queue.push(neighbor);
      }
    }
  }
}

const graph = {
  A: ['B', 'C'],
  B: ['A', 'D'],
  C: ['A', 'E'],
  D: ['B', 'E'],
  E: ['C', 'D']
};

BFS(graph, 'A');

2. Depth First Search (DFS):

function DFS(graph, start) {
  const visited = new Set();

  function dfsHelper(vertex) {
    visited.add(vertex);
    console.log(vertex);
    const neighbors = graph[vertex];
    for (const neighbor of neighbors) {
      if (!visited.has(neighbor)) {
        dfsHelper(neighbor);
      }
    }
  }

  dfsHelper(start);
}

const graph = {
  A: ['B', 'C'],
  B: ['A', 'D'],
  C: ['A', 'E'],
  D: ['B', 'E'],
  E: ['C', 'D']
};

DFS(graph, 'A');

3. Shortest path algorithm (such as Dijkstra's algorithm):

function Dijkstra(graph, start) {
  const distances = {};
  const visited = new Set();
  const queue = new PriorityQueue();

  for (const vertex in graph) {
    distances[vertex] = vertex === start ? 0 : Infinity;
    queue.enqueue(vertex, distances[vertex]);
  }

  while (!queue.isEmpty()) {
    const { element: vertex } = queue.dequeue();
    if (visited.has(vertex)) {
      continue;
    }
    visited.add(vertex);
    const neighbors = graph[vertex];
    for (const neighbor in neighbors) {
      const distance = distances[vertex] + neighbors[neighbor];
      if (distance < distances[neighbor]) {
        distances[neighbor] = distance;
        queue.updatePriority(neighbor, distance);
      }
    }
  }

  return distances;
}

const graph = {
  A: { B: 5, C: 2 },
  B: { A: 5, C: 1, D: 3 },
  C: { A: 2, B: 1, D: 2 },
  D: { B: 3, C: 2 }
};

console.log(Dijkstra(graph, 'A'));

These are JavaScript examples of some common graph algorithms. Graph algorithms are very useful in solving problems such as network connections, path search, and shortest paths.

Hope it helps you! If you have further questions, please feel free to ask.
 

Guess you like

Origin blog.csdn.net/weixin_39273589/article/details/132538964