Tìm kiếm theo chiều sâu (DFS)
C# Code
using System.Collections.Generic;
public class DFS {
// Ví dụ về việc duyệt một mê cung
public bool SolveMaze(Maze maze, Node start, Node end) {
Stack<Node> stack = new Stack<Node>();
HashSet<Node> visited = new HashSet<Node>();
stack.Push(start);
while (stack.Count > 0) {
Node current = stack.Pop();
if (current == end) {
return true; // Tìm thấy lối ra
}
if (!visited.Contains(current)) {
visited.Add(current);
foreach (Node neighbor in maze.GetNeighbors(current)) {
if (!visited.Contains(neighbor) && neighbor.isWalkable) {
stack.Push(neighbor);
}
}
}
}
return false; // Không tìm thấy lối ra
}
}Thuật toán tìm kiếm theo chiều sâu (DFS) đi sâu vào một nhánh cho đến khi hết đường, sau đó quay lại. Thường được dùng để giải mê cung hoặc duyệt cây dữ liệu (skill tree).