void xDigraph::DFS(size_t v) { // 所有顶点标记为未访问 for (size_t i = 0; i < marked.size(); i++) marked[i] = false; DepthFirstSearch(v); }
void xDigraph::DepthFirstSearch(size_t v) { visit(v); // 访问顶点v marked[v] = true; // 置该顶点为已访问 for (auto c_iter = AL[v].cbegin(); c_iter != AL[v].cend(); ++c_iter) if (!marked[*c_iter]) DepthFirstSearch(*c_iter); }
bool Graph::haveCycle(Edge edge) { bool marked[vertices.capacity()]; for (size_t i = 0; i < vertices.capacity(); ++i) marked[i] = false; DepthFirstSearch(marked, edge.destination->id); return marked[edge.source->id]; }
void Graph::DepthFirstSearch(bool marked[], size_t currentIndex) { marked[currentIndex] = true; if (vertices[currentIndex] != nullptr) { for (list<Edge *>::iterator eIt = vertices[currentIndex]->neighborhood.begin(); eIt != vertices[currentIndex]->neighborhood.end(); eIt++) { if (!marked[(*eIt)->destination->id]) { DepthFirstSearch(marked, (*eIt)->destination->id); } } } }
unsigned short MinMaxAlgorithm::GetNextPlay() { // if Graph is initiated, delete it if (this->aGraph) delete this->aGraph; // allocate a new graph this->aGraph = new Graph<u_int8_t>; // call DepthFirstSearch function return DepthFirstSearch(); }
static inline void DepthFirstSearch(int x, int y, int current_label, int NrPixels, int **BoolImage, int **ConnectedComponents,int **Positions, int *PositionTrackers) { if (x < 0 || x == NrPixels) return; if (y < 0 || y == NrPixels) return; if ((ConnectedComponents[x][y]!=0)||(BoolImage[x][y]==0)) return; ConnectedComponents[x][y] = current_label; Positions[current_label][PositionTrackers[current_label]] = (x*NrPixels) + y; PositionTrackers[current_label] += 1; int direction; for (direction=0;direction<8;++direction){ DepthFirstSearch(x + dx[direction], y + dy[direction], current_label, NrPixels, BoolImage, ConnectedComponents,Positions,PositionTrackers); } }
static inline int FindConnectedComponents(int **BoolImage, int NrPixels, int **ConnectedComponents, int **Positions, int *PositionTrackers){ int i,j; for (i=0;i<NrPixels;i++){ for (j=0;j<NrPixels;j++){ ConnectedComponents[i][j] = 0; } } int component = 0; for (i=0;i<NrPixels;++i) { for (j=0;j<NrPixels;++j) { if ((ConnectedComponents[i][j]==0) && (BoolImage[i][j] == 1)){ DepthFirstSearch(i,j,++component,NrPixels,BoolImage,ConnectedComponents,Positions,PositionTrackers); } } } return component; }
int main() { id_no = 0; int i,j; AdjList al; for(i=0; i<GRAPH_SIZE; i++) { al.list[i] = newVertex(); //printf("(%d).\n",al.list[i]->v->id_no); } AdjMatrix am; for(i=0; i<GRAPH_SIZE; i++) for(j=0; j<GRAPH_SIZE; j++) am.matrix[i][j] = INFINITE; edgepopulator(al,am,GRAPH_DENSITY); printf("No. of vertices = %d. No. of edges = %d.\n",GRAPH_SIZE,no_of_edges); fillAdjMatrix(al,am.matrix); //printAdjMatrix(am.matrix); clock_t start = clock(); visited_nodes; int question = 3; int answer = DepthFirstSearch(al,am,3,"ijlc",&visited_nodes); int dfs_count = visited_nodes; visited_nodes = 0; printf("%d.\n",BreadthFirstSearch(al,am,3,"ijlc",&visited_nodes)); int bfs_count = visited_nodes; int g_size = GRAPH_SIZE; float g_density = GRAPH_DENSITY; printf("Under the following conditions..\n"); printf("GRAPH_SIZE = %d.\n",g_size); printf("GRAPH_DENSITY = %f.\n", g_density); printf("Initial Distance = %d.\n", abs(answer-question)); printf("Results DFS(%d) vs BFS(%d).\n",dfs_count, bfs_count); return 0; }
//returns true if a directed path exists from start to target //true is of course 1, 0 is false int DepthFirstSearch(Node *start, Node *target, int colorVisit) { //fprintf(stderr, "%d %d %d\n", start->x, start->y, start->z); if (start == target) { return 1; } Edge *tempNext = start->edge; if (tempNext == NULL || start->color == colorVisit || start->dead == 1) { return 0; } else { start->color = colorVisit; int tempVal = 0; while (0 == tempVal && tempNext != NULL) { tempVal = DepthFirstSearch(tempNext->node, target, colorVisit); tempNext = tempNext->edge; } return tempVal; } }
void buildCycles(double *dist, int *segs, int sizeHeap, Parent *sets, Node *nodes, FILE *outputFile, int maxComponents) { //note: heap should already be built. int curHeapLength = sizeHeap; int unions= 0; //counters, useful for debugging int nons= 0; int continueFinding = 0; //increments when componentfound for (int i = sizeHeap - 1; i > -1 && maxComponents > continueFinding ; i--) { double minDist = GetAlphaDist(dist, 0); int fx = GetAlphaSeg(segs, 0, 0, 0); int fy = GetAlphaSeg(segs, 0, 1, 0); int fz = GetAlphaSeg(segs, 0, 2, 0); int tx = GetAlphaSeg(segs, 0, 0, 1); int ty = GetAlphaSeg(segs, 0, 1, 1); int tz = GetAlphaSeg(segs, 0, 2, 1); SwitchAlphas(dist, segs, 0, i); curHeapLength--; minHeapify(dist, segs, 0, curHeapLength); //fprintf(stderr, "%f\n", minDist); //fprintf(stderr, "%f (%d %d %d) (%d %d %d)\n", minDist, fx, fy, fz, tx, ty, tz); //now we process the two points. //fprintf(stderr, "%d %d\n", calcIndexN(fx, fy, fz), calcIndexN(tx, ty, tz)); //we need these several places int fromIndex = calcIndexN(fx,fy,fz); int toIndex = calcIndexN(tx,ty,tz); if (Value(sets[fromIndex]) != Value(sets[toIndex])) { Union(&sets[fromIndex], &sets[toIndex]); //and add edge to new graph from fx,y,z to tx,y,z Edge *newEdge = (Edge *)malloc(sizeof(Edge)); newEdge->node = &nodes[toIndex]; newEdge->edge = NULL; newEdge->dist = minDist; if (nodes[fromIndex].edge == NULL) { nodes[fromIndex].edge = newEdge; } else { Edge *temp = nodes[fromIndex].edge; while (temp->edge != NULL) { temp = temp->edge; } temp->edge = newEdge; } unions++; } else { //fprintf(stderr, "%d %d\n" ,Value(sets[calcIndexN(fx, fy, fz)]) ,Value(sets[calcIndexN(tx, ty, tz)])); //search, find and output! (or discard) int success = DepthFirstSearch(&nodes[toIndex], &nodes[fromIndex], nons); if (1 == success) { //fprintf(stderr, "cycle from %d %d %d to %d %d %d\n", tx, ty, tz, fx, fy, fz); nons++; continueFinding++; //stop processing if goes above maxComponents fprintf(outputFile, "Component %d of %d:\n", continueFinding, maxComponents); PrintCycle(&nodes[toIndex], &nodes[fromIndex], nons, outputFile); fprintf(outputFile, "\n"); } //do the following steps in this case no matter what, i.e. add the edge to the graph Edge *newEdge = (Edge *)malloc(sizeof(Edge)); newEdge->node = &nodes[toIndex]; newEdge->edge = NULL; newEdge->dist = minDist; if (nodes[fromIndex].edge == NULL) { nodes[fromIndex].edge = newEdge; } else { Edge *temp = nodes[fromIndex].edge; while (temp->edge != NULL) { temp = temp->edge; } temp->edge = newEdge; } nons++; } } //fprintf(stderr, "%d %d\n", unions, nons); }
int main(int argc, char *argv[]) { MyBtree<std::string> mbt; MyBtree<std::string> mbt2 { "hello","this","is","james" }; std::ifstream infile(argv[1]); if (!infile.good()) { std::cerr << "Could not open " << argv[1] << " for input!" << std::endl; std::exit(1); } std::string temp; while (infile >> temp) mbt.insert(temp); std::cout << "Created a binary tree of size: " << mbt.get_size() << " (" << mbt.get_left_depth() << "," << mbt.get_right_depth() << ")" << std::endl; std::cout << "Enter words that you want to check (ctrl-c to exit)" <<std::endl; while (std::cin >> temp) { std::cout << " Result of depth first search for: " << temp << " in: " << argv[1] << " is: " << std::boolalpha << DepthFirstSearch(mbt,temp) << std::endl; std::cout << " Result of breadth first search for: " << temp << " in: " << argv[1] << " is: " << std::boolalpha << BreadthFirstSearch(mbt2,temp) << std::endl; } }
// use a best-first search theorem prover int runbfsprover(List<Clause> &clist) { int status; // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } // copy clauses to a tree for better performance BinaryTree_AVL<Clause> ctree; ListIterator<Clause> clIter(clist); for (nextClause=1; !clIter.done(); clIter++) { // insert clauses at current deph Clause clause(clIter()); clause.setDepth(1); clause.setNumber(nextClause++); if (ctree.insert(clause) != OK) { ERROR("insert failed.", errno); return(NOTOK); } } // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } // list clauses cout << endl; cout << "===============================================" << endl; cout << "initial list of clauses: " << endl; BinaryTree_AVL_Iterator_InOrder<Clause> ctreeIter(ctree); for ( ; !ctreeIter.done(); ctreeIter++) { cout << ctreeIter() << endl; } cout << "===============================================" << endl; // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } // filter clauses if (removeTautologies(ctree) != OK) { ERROR("removeTautologies failed.", errno); return(NOTOK); } if (initialRemoveSubsumed(ctree) != OK) { ERROR("removeSubsumed failed.", errno); return(NOTOK); } // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } // separate clauses into SOS and axioms BinaryTree_AVL<Clause> soslist; BinaryTree_AVL<Clause> axiomlist; for (ctreeIter.reset(); !ctreeIter.done(); ctreeIter++) { if (ctreeIter().getSOS()) { if ((status = soslist.insert(ctreeIter())) != OK) { ERROR("insert failed.", errno); return(status); } } else { if ((status = axiomlist.insert(ctreeIter())) != OK) { ERROR("insert failed.", errno); return(status); } } } // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } // generate a list of possible resolution states List<BFSNode> bfsnodelist; BinaryTree_AVL_Iterator_InOrder<Clause> sosIter1(soslist); for ( ; !sosIter1.done(); sosIter1++) { if (sosIter1().getTotalMembers() > maxliterals) continue; Literal maxlit1; if (sosIter1().getMaximalLiteral(maxlit1) != OK) { ERROR("get maximal literal failed.", errno); return(NOTOK); } BinaryTree_AVL_Iterator_InOrder<Clause> sosIter2(sosIter1); for (sosIter2++ ; !sosIter2.done(); sosIter2++) { // generate possible resolution states Literal maxlit2; if (sosIter2().getMaximalLiteral(maxlit2) != OK) { ERROR("get maximal literal failed.", errno); return(NOTOK); } if (sosIter2().getTotalMembers() > maxliterals) { statistics[MaximumLiteralsClausesRejected] += 1; totalstatistics[TotalMaximumLiteralsClausesRejected] += 1; continue; } if (maxlit1.unify_ne(~maxlit2)) continue; BFSNode bfsnode(maxlit1, maxlit2, sosIter1(), sosIter2()); if (bfsnodelist.insertAtEnd(bfsnode) != OK) { ERROR("insert failed.", errno); return(status); } } BinaryTree_AVL_Iterator_InOrder<Clause> axiomIter(axiomlist); for ( ; !axiomIter.done(); axiomIter++) { // generate possible resolution states Literal maxlit2; if (axiomIter().getMaximalLiteral(maxlit2) != OK) { ERROR("get maximal literal failed.", errno); return(NOTOK); } if (axiomIter().getTotalMembers() > maxliterals) { statistics[MaximumLiteralsClausesRejected] += 1; totalstatistics[TotalMaximumLiteralsClausesRejected] += 1; continue; } if (maxlit1.unify_ne(~maxlit2)) continue; BFSNode bfsnode(maxlit1, maxlit2, sosIter1(), axiomIter()); if (bfsnodelist.insertAtEnd(bfsnode) != OK) { ERROR("insert failed.", errno); return(status); } } } // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } // call search routines switch (searchtype) { case BestFirst: status = BestFirstSearch(bfsnodelist, soslist, axiomlist); break; case DepthFirstHillClimb: status = DepthFirstHillClimbSearch(bfsnodelist, soslist, axiomlist); break; case DepthFirst: status = DepthFirstSearch(bfsnodelist, soslist, axiomlist); break; case BreadthFirst: status = BreadthFirstSearch(bfsnodelist, soslist, axiomlist); break; case IterativeDeepening: status = IterativeDeepeningSearch(bfsnodelist, soslist, axiomlist); break; default: ERRORD("unknown search type", searchtype, EINVAL); return(NOTOK); } // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } // report results of provers switch (status) { case OK: case VALID: // valid program programstatistics[TotalValidPrograms] += 1; cout << endl; cout << "Run Time Statistics ..." << endl; cout << statistics << endl; cout << endl; cout << "VALID program." << endl; // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } return(VALID); case NOTPROVEN: if (nextClause > maxclause) { programstatistics[TotalMaximumClauseExceededPrograms] += 1; ERROR("maxclause exceeded !!!", EINVAL); } else if (currentBFSDepth > maxdepth) { programstatistics[TotalMaximumDepthExceededPrograms] += 1; ERROR("maxdepth exceeded !!!", EINVAL); } programstatistics[TotalNotProvenPrograms] += 1; cout << endl; cout << "Run Time Statistics ..." << endl; cout << statistics << endl; cout << endl; cout << "NOTPROVEN program." << endl; // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } return(NOTPROVEN); default: // some type of error ERRORD("unexpected return from best first search !!!", status, EINVAL); // dump data info if (reportmemoryusage) { SETFINALEDATA(); DUMPDATA(cout); } return(status); } }