public bool DFSStack(GraphAM gph, int source, int target) { int count = gph.count; bool[] visited = new bool[count]; Stack <int> stk = new Stack <int>(); stk.Push(source); visited[source] = true; while (stk.Count > 0) { int curr = stk.Pop(); List <Edge> adl = gph.Adj[curr]; foreach (Edge adn in adl) { if (visited[adn.dest] == false) { visited[adn.dest] = true; stk.Push(adn.dest); } } } return(visited[target]); }
public bool SearchBFS(GraphAM gph, int source, int target) { int count = gph.count; bool[] visited = new bool[count]; Queue <int> que = new Queue <int>(); que.Enqueue(source); visited[source] = true; while (que.Count > 0) { int curr = que.Dequeue(); List <Edge> adl = gph.Adj[curr]; foreach (Edge adn in adl) { if (visited[adn.dest] == false) { visited[adn.dest] = true; que.Enqueue(adn.dest); } } } return(visited[target]); }
public bool dfs(GraphAM gph, int source, int target) { int count = gph.count; bool[] visited = new bool[count]; dfsUtil(gph, source, visited); return(visited[target]); }
public void dfsUtil(GraphAM gph, int index, bool[] visited) { visited[index] = true; List <Edge> adl = gph.Adj[index]; foreach (Edge adn in adl) { if (visited[adn.dest] == false) { dfsUtil(gph, adn.dest, visited); } } }
static void Main(string[] args) { GraphAM graph = new GraphAM(5); graph.AddDirectedEdge(1, 1, 3); graph.AddDirectedEdge(0, 4, 2); graph.AddDirectedEdge(1, 2, 1); graph.AddDirectedEdge(2, 3, 1); graph.AddDirectedEdge(4, 1, -2); graph.AddDirectedEdge(4, 3, 1); graph.Display(); WriteLine(graph.dfs(graph, 0, 2)); WriteLine(graph.SearchBFS(graph, 0, 2)); WriteLine(graph.DFSStack(graph, 0, 2)); ReadKey(); }