|
boolean visited[]; // denote whether a node has been visited |
|
public void dfs(int i)
{
int j;
visited[i] = true; // Mark node as "visited"
printNode(i);
for ( j = 0; j < NNodes; j++ )
{
if ( adjMatrix[i][j] > 0 && !visited[j] )
{
dfs(j); // Visit node
}
}
}
|
|
|
/* ===================================================
Dept First Traversal of a graph without recursion
=================================================== */
dfs()
{
pick a node x....
push(x);
visited[x] = true;
while ( stack != empty )
{
n = node at stack top (peek only);
nextNode = an unvisited node adjacent to n;
if ( nextNode exists )
{
visited[nextNode] = true;
push(nextNode); // Process this node first
}
else
{ /* -----------------------------------------------------
Node at top of stack has no unvisited neighbor nodes
----------------------------------------------------- */
pop(); // Move on to the next node on the stack
}
}
}
|