Exemple #1
0
 bool depthFirstSearch(TreeNode *root, int current, int sum) {
     if (root == NULL)
         return false;
     current += root->val;
     if (isLeaf(root))
         return current == sum;
     return depthFirstSearch(root->left, current, sum) || depthFirstSearch(root->right, current, sum);
 }
Exemple #2
0
// Internally uses DFS for graph traversal
bool NodeTree::checkCycle(NodeID startNode)
{
    // Initialize color map with white color
    std::vector<ENodeColor> colorMap(_nodes.size(), ENodeColor::White);

    return !depthFirstSearch(startNode, colorMap);
}
void StronglyConnectedComponents::findStronglyConnectedComponents() {
  for (DirectedGraph::node_id v = 0; v < directed_graph_.getNumNodes(); ++v) {
    if (!is_marked_[v]) {
      depthFirstSearch(v);
    }
  }
}
Exemple #4
0
int main(int argc, char **agv) {
    int i;
    int visited[SIZE];
    Graph *graph = initGraph(SIZE);

    printf("%d\n", sizeof(int **));
    graph->edgeMat[0][1] = 1;
    graph->edgeMat[0][2] = 1;
    graph->edgeMat[1][2] = 1;
    graph->edgeMat[2][0] = 1;
    graph->edgeMat[2][3] = 1;
    graph->edgeMat[3][3] = 1;

    for(i = 0; i < graph->V; i++) {
        visited[i] = 0;
    }
    printf("DFS rec ");
    depthFirstSearch(graph, visited, 2);
    
    for(i = 0; i < graph->V; i++) {
        visited[i] = 0;
    }

    printf("\n DFS non_rec ");
    depthFirstSearchNonRec(graph, visited, 2);

    printf("\n BFS non_rec");
    breadthFirstSearch(graph, 2);

    releaseGraph(graph);
    return 0;
}
Exemple #5
0
void Graph::search(SearchType searchType) {

    vector<Vertex *> vertexes = getVertexes();

    for (vector<Vertex *>::iterator it = vertexes.begin(); it != vertexes.end(); it++) {

        Vertex *vertex = *it;

        vertex->setVisited(false);
    }

    for (vector<Vertex *>::iterator it = vertexes.begin(); it != vertexes.end(); it++) {

        Vertex *vertex = *it;

        if (!vertex->getVisited()) {

            switch (searchType) {

                case DEPTH:
                    depthFirstSearch(vertex);
                    break;

                case BREADTH:
                    breadthFirstSearch(vertex);
                    break;

                case WEIGHT:
                    updateAllWeight(vertex);
            }
        }
    }
}
Exemple #6
0
int main(){
    unsigned k;
    for(k = 0; k < n; k++){ used[k] = 0; }
    printf("Depth Search from %u: \n", v);
    depthFirstSearch(v - 1);
    printf("\n");
    return 0;
}
Exemple #7
0
void depthFirstSearch(unsigned i){
    unsigned k;
    used[i] = 1;
    printf("%u ", i + 1);
    for(k = 0; k < n ; k++){
        if(!used[k] && A[i][k]) depthFirstSearch(k);
    }
}
std::vector<size_t> CGraph::rebuildWay()
{
    std::vector<bool> visited(verticesAmount, false);
    std::vector<size_t> way;
    depthFirstSearch(0, visited, way);
    way.push_back(0);
    return way;
}
Exemple #9
0
// Internally uses DFS for graph traversal (in fact it's topological sort)
void NodeTree::prepareListImpl()
{
    // Initialize color map with white color
    std::vector<ENodeColor> colorMap(_nodes.size(), ENodeColor::White);

    _executeList.clear();

    // For each invalid nodes (in terms of executable) mark them black
    // so "true" graph traversal can skip them
    for(NodeID nodeID = 0; nodeID < NodeID(_nodes.size()); ++nodeID)
    {
        if(!validateNode(nodeID))
            continue;

        if(colorMap[nodeID] != ENodeColor::White)
            continue;

        if(isNodeExecutable(nodeID))
            continue;

        if(!depthFirstSearch(nodeID, colorMap))
            return;
    }	

    // For each tagged and valid nodes that haven't been visited yet do ..
    for(NodeID nodeID = 0; nodeID < NodeID(_nodes.size()); ++nodeID)
    {
        if(!validateNode(nodeID))
            continue;

        if(colorMap[nodeID] != ENodeColor::White)
            continue;

        if(!_nodes[nodeID].flag(ENodeFlags::Tagged))
            continue;

        if(!depthFirstSearch(nodeID, colorMap, &_executeList))
        {
            _executeList.clear();
            return;
        }
    }

    // Topological sort gives result in inverse order
    std::reverse(std::begin(_executeList), std::end(_executeList));
}
Exemple #10
0
void LoopReductor::processWorkSpace(otawa::WorkSpace *fw) {

	int idx = 0;

	const CFGCollection *orig_coll = INVOLVED_CFGS(fw);
	if (reduce_loops) {

		for (CFGCollection::Iterator cfg(*orig_coll); cfg; cfg++) {
			VirtualCFG *vcfg = new VirtualCFG(false);
			if (ENTRY_CFG(fw) == *cfg)
				ENTRY_CFG(fw) = vcfg;
			vcfgvec.add(vcfg);
			INDEX(vcfg) = INDEX(cfg);
			LABEL(vcfg) = LABEL(cfg);
			ENTRY(vcfg->entry()) = vcfg;

		}

		int i = 0;
		for (CFGCollection::Iterator cfg(*orig_coll); cfg; cfg++, i++) {
			VirtualCFG *vcfg = vcfgvec.get(i);

			idx = 0;
			INDEX(vcfg->entry()) = idx;
			vcfg->addBB(vcfg->entry());
			idx++;

			reduce(vcfg, cfg);

			INDEX(vcfg->exit()) = idx;
			vcfg->addBB(vcfg->exit());

			/* Renum basic blocks */
			idx = 0;
			for (CFG::BBIterator bb(vcfg); bb; bb++) {
				INDEX(bb) = idx;
				idx++;
			}
		}

	INVOLVED_CFGS(fw) = NULL;
	} else {
		for (CFGCollection::Iterator cfg(*orig_coll); cfg; cfg++) {

			Vector<BasicBlock*> *ancestors = new Vector<BasicBlock*>();

			for (CFG::BBIterator bb(cfg); bb; bb++) {
				IN_LOOPS(bb) = new dfa::BitSet(cfg->countBB());
			}

			/* Do the Depth-First Search, compute the ancestors sets, and mark loop headers */
			depthFirstSearch(cfg->entry(), ancestors);
			delete ancestors;
		}

	}

}
Exemple #11
0
void Tree<T>::depthFirstSearch(const Graph<T>& graph, const T& node)
{
	try {
		unsigned idx = graph.searchNode(node);
		depthFirstSearch(graph, idx);
	}
	catch (...) {
	}
}
void DungeonGenerator::ConnectAllUnconnectedRooms(Dungeon* dungeon) const
{
	auto* connectedRooms = new std::vector<Room*>;
	auto foundRoomToConnectTo = false;

	for (auto floorIndex = 0; floorIndex < MAX_DUNGEON_LEVEL; ++floorIndex)
	{
		connectedRooms->clear();

		depthFirstSearch(dungeon->getRoom(0, 0, floorIndex), connectedRooms);

		for (auto x = 0; x < dungeon->getWidth(); ++x)
		{
			for (auto y = 0; y < dungeon->getHeight(); ++y)
			{
				if (std::find(connectedRooms->begin(), connectedRooms->end(), dungeon->getRoom(x, y, floorIndex)) == connectedRooms->end())
				{
					if (y > 0 && std::find(connectedRooms->begin(), connectedRooms->end(), dungeon->getRoom(x, (y - 1), floorIndex)) != connectedRooms->end())
					{
						dungeon->createDirection(x, y, floorIndex, Direction::NORTH);
						foundRoomToConnectTo = true;
					}

					if (x < (dungeon->getWidth() - 1) && std::find(connectedRooms->begin(), connectedRooms->end(), dungeon->getRoom((x + 1), y, floorIndex)) != connectedRooms->end())
					{
						dungeon->createDirection(x, y, floorIndex, Direction::EAST);
						foundRoomToConnectTo = true;
					}

					if (y < (dungeon->getHeight() - 1) && std::find(connectedRooms->begin(), connectedRooms->end(), dungeon->getRoom(x, (y + 1), floorIndex)) != connectedRooms->end())
					{
						dungeon->createDirection(x, y, floorIndex, Direction::SOUTH);
						foundRoomToConnectTo = true;
					}

					if (x > 0 && std::find(connectedRooms->begin(), connectedRooms->end(), dungeon->getRoom((x - 1), y, floorIndex)) != connectedRooms->end())
					{
						dungeon->createDirection(x, y, floorIndex, Direction::WEST);

						foundRoomToConnectTo = true;
					}

					if (foundRoomToConnectTo)
					{
						ConnectAllUnconnectedRooms(dungeon);

						delete connectedRooms;
						return;
					}
				}
			}
		}
	}

	delete connectedRooms;
}
void depthFirstSearch(Node node, char* visited, int* count) {
	printf("%c", node.name);
	visited[*count] = node.name; *count = *count + 1;
	if (node.neighborCount != 0) {
		for (int i = 0; i < node.neighborCount; i++) {
			if(!alreadyVisited(visited, node.neighbors[i]->name, *count))
				depthFirstSearch(*node.neighbors[i], visited, count);
		}
	}
}
Exemple #14
0
void verifyGraph (tGraph ** pGraph)
{
	int i, j;

	char * visited;

	char * order;

	depthFirstSearch (&(*pGraph), &visited, &order);

	/***********************************/
	printf("graph:\n");
	for(i=0; i<(*pGraph)->size; i++)
	{
		for (j=0; j < (*pGraph)->nodesList[i]->size; j++)
		{
			printf("%c ", (*pGraph)->nodesList[i]->adjList[j]->name);
		}
		printf("\n");
	}
	/***********************************/
	printf("visited list:\n");
	for (i=0; i<(*pGraph)->size; i++)
	{
		printf("%d ", (visited)[i]);
	}
	printf("\n");
	free (visited);
	/***********************************/
	printf("visitation order:\n");
	for (i=0; order[i]!=0; i++){
		printf("%c ", (order)[i]);
	}
	printf("\n");
	free (order);
	/***********************************/
	printf("size of adjacency list of each node:\n");
	for (i=0; i<(*pGraph)->size; i++)
	{
		printf("%d ", (*pGraph)->nodesList[i]->size);
	}
	printf("\n");
	/***********************************/
	printf("id of each node:\n");
	for (i=0; i<(*pGraph)->size; i++)
	{
		printf("%d ", (*pGraph)->nodesList[i]->id );
	}
	printf("\n");
	/***********************************/
	


}
Exemple #15
0
void depthFirstSearch(Graph *graph, int visited[], int vertex) {
    int i;
    visited[vertex] = 1;
    printf(" %d", vertex);
    for(i = 0; i < graph->V; i++) {
        if(graph->edgeMat[vertex][i] == 1) {
            if(visited[i] != 1) {
                depthFirstSearch(graph, visited, i);
            }
        }
    }
}
Exemple #16
0
int Master::enumerationStrategy(const Sub *s1, const Sub *s2)
{
	switch (enumerationStrategy_) {
	case BestFirst:    return bestFirstSearch(s1, s2);
	case BreadthFirst: return breadthFirstSearch(s1, s2);
	case DepthFirst:   return depthFirstSearch(s1, s2);
	case DiveAndBest:  return diveAndBestFirstSearch(s1, s2);
	default:
		Logger::ifout() << "Master::enumerationStrategy(): Unknown enumeration strategy\n";
		OGDF_THROW_PARAM(AlgorithmFailureException, ogdf::AlgorithmFailureCode::IllegalParameter);
	}
}
int depthFirstSearch(int a[10][10], int n, int source, int visited[100]) {
    int i;

    printf("%d\t", source);
    visited[source] = 1;
    count++;

    for (i = 1; i <= n; i++)
        if (visited[i] == 0 && a[source][i] == 1)
            depthFirstSearch(a, n, i, visited);

    return 0;
}
Exemple #18
0
void dominatorCFG::depthFirstSearch(dominatorBB *v) {
   v->dfs_no = currentDepthNo++;
   sorted_blocks.push_back(v);
   v->semiDom = v;
   for (unsigned i=0; i<v->succ.size(); i++) 
   {
      dominatorBB* successor = v->succ[i];
      if (successor->dfs_no != -1)
         continue;
      successor->parent = v;
      depthFirstSearch(successor);
   }
}
void CGraph::depthFirstSearch(size_t vertexIndex, std::vector<bool> &visited, std::vector<size_t> &way)
{
    assert(vertexIndex < verticesAmount);
    visited[vertexIndex] = true;
    way.push_back(vertexIndex);
    for (size_t i = 0; i < edgesList[vertexIndex].size(); ++i)
    {
        size_t nextVertexIndex = edgesList[vertexIndex][i].secondVertexIndex;
        if (!visited[nextVertexIndex])
        {
            depthFirstSearch(nextVertexIndex, visited, way);
        }
    }
}
void DungeonGenerator::depthFirstSearch(Room* room, std::vector<Room*>* connectedRooms) const
{
	connectedRooms->push_back(room);

	typedef std::map<Direction, Room*>::iterator it_room;

	for (auto it = room->getRooms()->begin(); it != room->getRooms()->end(); ++it)
	{
		if (std::find(connectedRooms->begin(), connectedRooms->end(), it->second) == connectedRooms->end())
		{
			depthFirstSearch(it->second, connectedRooms);
		}
	}
}
	public void depthFirstSearch(Vertex v)
	{

	v.visited = true;
	// print the node
	for(each vertex w adjacent to v)
	{

	if(!w.visited)
	{

	depthFirstSearch(w);
	}
	}
	}
Exemple #22
0
void Graph::depthFirstSearch(Vertex *vertex) {

    vertex->setVisited(true);
    vector<Adjacency *> adjacencies = vertex->getAdjacencies();

    vertex->showGeneratorTree();

    for (vector<Adjacency *>::iterator it = adjacencies.begin(); it != adjacencies.end(); it++) {

        Adjacency *adjacency = *it;

        Vertex *nextVertex = adjacency->getCorner()->getConvergent();

        if (!nextVertex->getVisited()) {
            depthFirstSearch(nextVertex);
        }
    }
}
Exemple #23
0
void LoopReductor::depthFirstSearch(BasicBlock *bb, Vector<BasicBlock*> *ancestors) {
	ancestors->push(bb);
	MARK(bb) = true;


	SortedSLList<Edge*, EdgeDestOrder> successors;
	for (BasicBlock::OutIterator edge(bb); edge; edge++)
		successors.add(*edge);

	for (SortedSLList<Edge*, EdgeDestOrder>::Iterator edge(successors); edge; edge++) {
		if ((edge->kind() != Edge::CALL) && !edge->target()->isExit()){
			if (MARK(edge->target()) == false) {
				depthFirstSearch(edge->target(), ancestors);
			} else {
				if (ancestors->contains(edge->target())) {
					LOOP_HEADER(edge->target()) = true;
					BACK_EDGE(edge) = true;
					bool inloop = false;
					for (Vector<BasicBlock*>::Iterator member(*ancestors); member; member++) {
						if (*member == edge->target())
							inloop = true;
						if (inloop) {
							IN_LOOPS(member)->add(edge->target()->number());
						}

					}
				}
				/* GRUIIIIIIIIIK !!! pas performant, mais bon.. */
				for (dfa::BitSet::Iterator bit(**IN_LOOPS(edge->target())); bit; bit++) {
					bool inloop = false;
					for (Vector<BasicBlock*>::Iterator member(*ancestors); member; member++) {
						if (member->number() == *bit)
							inloop = true;
						if (inloop) {
							IN_LOOPS(member)->add(*bit);
						}

					}
				}
			}
		}
	}
	ancestors->pop();
}
Exemple #24
0
void dominatorCFG::performComputation() {
   unsigned i, j;
   depthFirstSearch(entryBlock);
   for (i = sorted_blocks.size()-1; i > 0; i--)
   {
      dominatorBB *block = sorted_blocks[i];
      dominatorBB *parent = block->parent;
      if (block->dfs_no == -1)
         //Easy to get when dealing with un-reachable code
         continue;

      for (j = 0; j < block->pred.size(); j++)
      {
         dominatorBB *pred = block->pred[j]->eval();
         if (pred->sdno() < block->sdno())
            block->semiDom = pred->semiDom;
      }

      block->semiDom->bucket += block;
      link(parent, block);
      
      while (!parent->bucket.empty())
      {
         dominatorBB *u, *v;
         parent->bucket.extract(v);
         u = v->eval();
         if (u->sdno() < v->sdno())
            v->immDom = u;
         else
            v->immDom = parent;
      }
   }

   for (i = 1; i < sorted_blocks.size(); i++) {
      dominatorBB *block = sorted_blocks[i];
      if (block->immDom != block->semiDom)
         if (block->immDom)
            block->immDom = block->immDom->immDom;
         else
            block->immDom = NULL;
   }

   storeDominatorResults();
}
int _tmain(int argc, _TCHAR* argv[])
{
	Graph* graph = new Graph;
	Node* nodes = new Node[7];

	for (int i = 0; i < 7; ++i)
	{
		nodes[i].value = i;
		graph->allNodes.push_back(&nodes[i]);
	}

	nodes[0].neighbor.push_back(&nodes[1]);

	nodes[1].neighbor.push_back(&nodes[0]);
	nodes[1].neighbor.push_back(&nodes[5]);
	nodes[1].neighbor.push_back(&nodes[2]);

	nodes[2].neighbor.push_back(&nodes[1]);
	nodes[2].neighbor.push_back(&nodes[4]);
	nodes[2].neighbor.push_back(&nodes[3]);

	nodes[3].neighbor.push_back(&nodes[2]);

	nodes[4].neighbor.push_back(&nodes[2]);

	nodes[5].neighbor.push_back(&nodes[6]);
	nodes[5].neighbor.push_back(&nodes[2]);

	nodes[6].neighbor.push_back(&nodes[5]);
	//makeGraph(graph, nodes);
	depthFirstSearch(graph);

	getchar();
	getchar();

	delete graph;
	delete[] nodes;
	
	return 0;
}
int main() {
	Graph graph;
	initGraph(&graph);

	char input[100];

	//read console input and build graph
	//while (1) {
	//	if (fgets(input, 100, stdin)) { //fgets returns NULL at EOF (EOF in VS cmd line: enter ctrl+z enter)
	//		buildGraphFromInput(input, &graph);
	//	}
	//	else
	//		break;
	//}

	//debug only
	//one possible output: ADEFBCGHIJ\n
	buildGraphFromInput("A-BD\n", &graph);
	buildGraphFromInput("B-ACHI\n", &graph);
	buildGraphFromInput("C-BG\n", &graph);
	buildGraphFromInput("D-AEF\n", &graph);
	buildGraphFromInput("E-D\n", &graph);
	buildGraphFromInput("F-D\n", &graph);
	buildGraphFromInput("G-C\n", &graph);
	buildGraphFromInput("H-B\n", &graph);
	buildGraphFromInput("I-BJ\n", &graph);
	buildGraphFromInput("J-I\n", &graph);

	//traverse graph with DFS
	if (graph.nodeCount > 0) {
		char* visited = (char*)malloc(graph.nodeCount*sizeof(char)); int count = 0;
		depthFirstSearch(graph.nodes[0], visited, &count);
	}
	printf("\n");

	

	return EXIT_SUCCESS;
}
Exemple #27
0
void 
VrpNetwork::depthFirstSearch(vertex *v, int *count1, int *count2)
{
   register elist *e;
   bool has_child = false, has_non_tree_edge = false;
   bool is_art_point = false;
   int c, min;
   
   v->scanned = false;
   min = v->dfnumber = ++(*count1);
   for (e = v->first; e; e = e->next_edge){
      if (!e->other_end) continue;
      if (!e->other->scanned){
	 e->data->tree_edge = true;
	 depthFirstSearch(e->other, count1, count2);
	 has_child = true;
      }
      c = e->other->dfnumber;
      if (e->data->tree_edge && (c > v->dfnumber)){
	 if (min > e->other->low)
	    min = e->other->low;
	 if (e->other->low < v->dfnumber)
	    is_art_point = false;
      }else if (!e->data->tree_edge){
	 has_non_tree_edge = true;
	 if (c < v->dfnumber){
	    if (min > c){
	       min = c;
	    }
	 }
      }
   }
   v->low = min;
   if (!has_child && has_non_tree_edge) is_art_point = false;
   v->is_art_point = is_art_point;

   return;
}
std::vector<State*> SearchTree::doSearch(std::string algorithm)
{
    double startT, finishT;
    #ifdef __unix
    timespec startWallTime, finishWallTime;
    clock_gettime(CLOCK_MONOTONIC, &startWallTime);
    #else
    GET_TIME(startT);
    #endif
    std::clock_t startCpuTime = std::clock();

    if (algorithm == "bcktrk")
        solution = backTracking(root);
    else if (algorithm == "dfs")
        solution = depthFirstSearch(dfsDepthLimit);
    else if (algorithm == "bfs")
        solution = breadthFirstSearch();
    else if (algorithm == "ucs")
        solution = orderSearch();
    else if (algorithm == "greedy")
        solution = greedy();
    else if (algorithm == "astr")
        solution = AStar();
    else if (algorithm == "idastr")
        solution = IDAStar();

    searchCpuTime = (std::clock() - startCpuTime) / (double)CLOCKS_PER_SEC;
    #ifdef __unix
    clock_gettime(CLOCK_MONOTONIC, &finishWallTime);
    searchWallTime = (finishWallTime.tv_sec - startWallTime.tv_sec) + (finishWallTime.tv_nsec - startWallTime.tv_nsec) / 1000000000.0;
    #else
    GET_TIME(finishT);
    searchWallTime = finishT - startT;
    #endif
    return getPathTo(solution);
}
int main() {
    int n, a[10][10], i, j, source, visited[100] = {0};

    printf("Enter the number of nodes: ");
    scanf("%d", &n);

    printf("Enter the adjacency matrix:\n");
    for (i = 1; i <= n; i++)
        for (j = 1; j <= n; j++)
            scanf("%d", &a[i][j]);

    printf("Enter the source node: ");
    scanf("%d", &source);

    printf("The Depth First Search Traversal is:\n");
    depthFirstSearch(a, n, source, visited);

    if (count == n)
        printf("\nThe graph is connected!");
    else
        printf("\nThe graph is not connected!");

    return 0;
}
Exemple #30
0
int Master::diveAndBestFirstSearch(const Sub *s1, const Sub* s2) const
{
	if (feasibleFound()) return bestFirstSearch(s1, s2);
	else                 return depthFirstSearch(s1, s2);
}