DFS是一種常見的圖形搜索演算法,用於遍歷和搜索圖形或樹狀結構。通常用於查找路徑、尋找連通性、拓撲排序等問題。DFS的基本思想是沿著一條路徑盡可能深入地遍歷,直到無法繼續為止,然後返回並嘗試其他路徑。
using System;
using System.Collections.Generic;
class Graph
{
private int V;
private List<int>[] adj;
public Graph(int v)
{
V = v;
adj = new List<int>[v];
for (int i = 0; i < v; ++i)
{
adj[i] = new List<int>();
}
}
public void AddEdge(int v, int w)
{
adj[v].Add(w);
}
public void DFS(int v)
{
bool[] visited = new bool[V];
DFSUtil(v, visited);
}
private void DFSUtil(int v, bool[] visited)
{
visited[v] = true;
Console.Write(v + " ");
foreach (int i in adj[v])
{
if (!visited[i])
{
DFSUtil(i, visited);
}
}
}
}
class Program
{
static void Main(string[] args)
{
Graph g = new Graph(7);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(1, 3);
g.AddEdge(1, 4);
g.AddEdge(2, 5);
g.AddEdge(2, 6);
Console.WriteLine("深度優先搜尋結果:");
g.DFS(0);
}
}
期望挑戰30天持續更新成功 ~ DAY24