public void dfs(UndirectedGraph g, int vertex){ marked[vertex] = true; id[vertex] = count; size[vertex]++; ArrayList adjacent = g.Adjacent(vertex); for (int i = 0; i < adjacent.Count; i++) { int currentVertex = (int) adjacent[i]; if(!marked[currentVertex]){ dfs(g, currentVertex); } } }
//do a depth first search on a vertex to find out all the vertices it has a path to. This also prints out all the vertices public void search(UndirectedGraph graph, int vertex) { totalPaths++; marked[vertex] = true; ArrayList adj = graph.Adjacent(vertex); path.Enqueue(vertex); //this is how it traverses //Console.WriteLine(vertex); for(int i = 0; i< adj.Count; i++) { int currentVertex = (int) adj[i]; if (marked[currentVertex] != true) { search(graph, currentVertex); } } }
public void bfs(UndirectedGraph g, int vertex) { Queue<int> q = new Queue<int>(); //set up the entire visitedMatrix with -1 except for the vertex node for (int i = 0; i < g.getTotalVertices(); i++) { visitedMatrix[i] = State.Unvisited; } //mark root with 1 to sat it's visited visitedMatrix[vertex] = State.Visiting; q.Enqueue(vertex); while (q.Count > 0) { int v = q.Dequeue(); Console.WriteLine(v); marked[v] = true; //get all adjacent ArrayList adj = g.Adjacent(v); for (int i = 0; i < adj.Count; i++) { int currentVertex = (int) adj[i]; if (visitedMatrix[currentVertex] == State.Unvisited) { q.Enqueue(currentVertex); visitedMatrix[currentVertex] = State.Visiting; } } visitedMatrix[v] = State.Visited; marked[v] = false; } }
public int[] getShortestPath(UndirectedGraph g, int vertex) { Queue<int> q = new Queue<int>(); q.Enqueue(vertex); //set up the entire distance matrix with -1 except for the vertex node for (int i = 0; i < g.getTotalVertices(); i++) { distanceMatrix[i] = -1; } //set up current vertex with 0 because there will be no distance distanceMatrix[vertex] = 0; while (q.Count > 0) { int v = q.Dequeue(); Console.Write(v); //this is the breadth first traversal ArrayList adjacent = g.Adjacent(v); //loop through all the adjacent nodes, if the currentVertex is still -1, then go in and do process for (int i = 0; i < adjacent.Count; i++) { int currentVertex = (int)adjacent[i]; if (distanceMatrix[currentVertex] == -1) { //add one to the distanceMatrix here because it's going to be from v to the current path distanceMatrix[currentVertex] = distanceMatrix[v] + 1; pathMatrix[currentVertex] = v; q.Enqueue(currentVertex); } } } return distanceMatrix; }