Skip to main content

Command Palette

Search for a command to run...

[DSA] Graph Traversal

Published
1 min readView as Markdown
[DSA] Graph Traversal

Giới thiệu

Có 2 cách duyệt Graph:

  • Depth First Search (DFS)

  • Breadth First Search (BFS)

Depth First Search (DFS)

Có 2 cách để thực thi DFS

  • Dùng đệ quy

  • Dùng vòng lặp

DFS Recursive

 depthFirstRecursive(start) {
    const result = [];
    const visited = {};

    (function dfs(vertex) {
      if (!vertex) {
        return null;
      }

      visited[vertex] = true;
      result.push(vertex);
      console.log(this.adjacencyList[vertex]);
    })(start);
  }

DFS Iterative

depthFirstIterative(start) {
    const stack = [start];
    const result = [];
    const visited = {};
    let currentVertex;

    visited[start] = true;
    while (stack?.length) {
      currentVertex = stack.pop();
      result.push(currentVertex);

      this.adjacencyList[currentVertex]?.forEach((neighbor) => {
        if (!visited[neighbor]) {
          visited[neighbor] = true;
          stack.push(neighbor);
        }
      });
    }

    return result;
  }

Breadth First Search (DFS)

breadthFirst(start) {
    const queue = [start];
    const result = [];
    const visited = {};
    let currentVertex;

    visited[start] = true;
    while (queue?.length) {
      currentVertex = queue.shift();
      result.push(currentVertex);

      this.adjacencyList[currentVertex]?.forEach((neighbor) => {
        if (!visited[neighbor]) {
          visited[neighbor] = true;
          queue.push(neighbor);
        }
      });
    }

    return result;
  }

Cấu trúc dữ liệu và giải thuật

Part 8 of 8

Đây là những chia sẻ và ghi chú của mình trong "Hành trình học cấu trúc dữ liệu và giải thuật.". Kiến thức mình học được chủ yếu lấy từ khoá học "JavaScript Algorithms and Data Structures Masterclass" của Thầy "Colt Steele" trên Udemy.

Start from the beginning

[DSA] Độ phức tạp của thuật toán Big O

Vấn đề Nếu có nhiều function thực hiện cùng 1 chức năng thì dựa vào đâu mà ta xác định được function nào là tốt nhất? Cơ sở nào để đánh giá code performance, trade-offs khi lựa chọn các cách tiếp cận? Làm thế nào để đánh giá được đoạn code nào là tốt...

More from this blog

Learning Journey

14 posts