http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/Graph/dfs.html
Iterative Version:
http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/Graph/Progs/dfs/Graph2.java
public void dfs() {
// DFS uses Stack data structure
Stack<Integer> s = new Stack<Integer>();
s.push(rootNode);
visited[rootNode] = true;
printNode(rootNode);
while (!s.isEmpty()) {
int n, child;
n = (s.peek()).intValue();
child = getUnvisitedChildNode(n);
if (child != -1) {
visited[child] = true;
printNode(child);
s.push(child);
} else {
s.pop();
}
}
clearVisited(); // Clear visited property of nodes
}
int getUnvisitedChildNode(int n) {
int j;
for (j = 0; j < NNodes; j++) {
if (adjMatrix[n][j] > 0) {
if (!visited[j])
return (j);
}
}
return (-1);
}
Recursive Version:
http://algs4.cs.princeton.edu/41undirected/DepthFirstSearch.java.html
public DepthFirstSearch(Graph G, int s) { marked = new boolean[G.V()]; dfs(G, s); } // depth first search from v private void dfs(Graph G, int v) { count++; marked[v] = true; for (int w : G.adj(v)) { if (!marked[w]) { dfs(G, w); } } }
BFS
https://gist.github.com/gennad/791932
public void bfs()
{
// BFS uses Queue data structure
Queue queue = new LinkedList();
queue.add(this.rootNode);
printNode(this.rootNode);
rootNode.visited = true;
while(!queue.isEmpty()) {
Node node = (Node)queue.remove();
Node child=null;
while((child=getUnvisitedChildNode(node))!=null) {
child.visited=true;
printNode(child);
queue.add(child);
}
}
}