CCN Interview Question
Applications DevelopersCountry: United States
Interview Type: Written Test
C++ code:
DFS, marks nodes as visited when going in, unvisited when going out, stops at destination node and outputs path.
#include <string>
#include <list>
#include <iostream>
class Node;
class Node
{
public:
std::string name;
std::list<Node*> adjacent; // list of adjacent nodes
bool visited;
};
void search_path ( Node& node, Node& destination, std::string path )
{
if ( node.visited )
return;
if ( &node == &destination )
{
std::cout << path + node.name << std::endl;
return;
}
node.visited = true;
std::string path_so_far = path + node.name + "--";
for ( std::list<Node*>::iterator iter = node.adjacent.begin(); iter!=node.adjacent.end(); iter++ )
{
search_path ( **iter, destination, path_so_far );
}
node.visited = false;
}
int main()
{
//Construct nodes and connect them + initialize their member "visited" to false;
//....
search_path(node1,node2,"");
return 0;
}
* code performs DFS and checks for all possible paths between s and t .
- salvo4u May 08, 2012* mat is the sqaure matrix of size n*n.
* list in recursion maintains all the paths