void PrintPath ( BinarryTree* pNode, int nExpectedSum, std::vector<int> path, int currentSum ) { currentSum += pNode->m_nValue; path.push_back(pNode->m_nValue); //如果是叶结点,并且路径上的值等于输入的值 //打印出这条路径 bool isLeaf = pNode->m_pLeft==NULL && pNode->m_pRight==NULL; if(currentSum==nExpectedSum && isLeaf) { cout << "A path is found:"; std::vector<int>::iterator iter = path.begin(); for(;iter!=path.end();iter++) cout << *iter << " "; cout << endl; } //如果不是叶结点,则遍历它的子结点 if(pNode->m_pLeft!=NULL) PrintPath(pNode->m_pLeft,nExpectedSum,path,currentSum); if(pNode->m_pRight!=NULL) PrintPath(pNode->m_pRight,nExpectedSum,path,currentSum); //在往上回溯的过程中删除结点 currentSum -= pNode->m_nValue; path.pop_back(); }
menu_items_t printmenuDestination(mxml_node_t *tree) { mxml_node_t *Destination=NULL; system("clear"); printf("Destination\n-----------\n\n"); Destination = mxmlFindElement(tree, tree, /*Search from the top*/ "Destination", NULL, NULL, /*The Destination element*/ MXML_DESCEND); /*Descending*/ /*the search might return null*/ if ( Destination != NULL ) { printf("01) Title: %s\n",getElemData(Destination,"Title") ); /*Now, lets search the hotsync*********************************************/ printf("02) HotSync:\n"); PrintPath(Destination,"HotSync"); /*Now, lets search the ActiveSync ***************************************/ printf("03) ActiveSync:\n"); PrintPath(Destination,"ActiveSync"); /*Now, lets search the Files ***************************************/ printf("05) Files:\n"); PrintPath(Destination,"Files"); printf("\n"); /*make it pretty*/ }/*end of the Destination procesing*/ else { /*No destination node, print empty*/ printf("01) Title: <n/a>\n" "02) HotSync:\n" "\t<n/a>\n" "03) ActiveSync:\n" "\t<n/a>\n" "04) Files:\n" "\t<n/a>\n"); } return MENU_DESTINATION; }
void tsp_partiel (int hops, int len, Path_t path, int *cuts) { int i ; int me, dist ; if (len >= minimum) { (*cuts)++ ; return; } if (hops == MINNBHOPS) { #ifdef DEBUG PrintPath("Add job : ", hops, path); #endif add_job (&listeTaches, path, hops, len); } else { me = path [hops-1] ; for (i=0; i < NbCities; i++) { if (!present (i, hops, path)) { path [hops] = i ; dist = distance[me][i] ; tsp_partiel (hops+1, len+dist, path, cuts) ; } } } }
int CBellman_MTK::Output(char *filename) { ofstream f; f.open(filename); if (!f) return 0; float A[100]; Print(A); f << setiosflags(ios::fixed); for (int i = 0; i < m_DoThi.LaySoDinh(); ++i) { f << setprecision(0) << A[i] << " "; char B[100]; int n; n = PrintPath(i + 1, B); for (int j = n - 1; j >= 0; --j) cout << (int) B[j] << " "; cout << endl; } return 1; }
int main(int argc, const char * argv[]) { Player player; PathSegment *path = GenerateAdventure(); PrintPath(path); player.current = path; player.current->direction = DirectionMain; player.health = 100; char input[300]; while (playing) { pathPrompt(&player); if(playing){ scanf("%s", input); printf("input was %s\n", input); if(strstr(input,"Y")) movePlayer(&player,DirectionMain); else movePlayer(&player,DirectionSide); printPlayerStatus(&player); } } FreeAllPathSegments(path); return 0; }
bool AStar::Step(sf::RectangleShape board[]) { Node* pCurrentNode; if (!qOpenList.empty()) { pCurrentNode = VisitNode(); } else { std::cout << "Can't find a path" << std::endl; return true; } UpdateBoardGraphic(board); if (pCurrentNode == tRoot[iEndNode]) { PrintPath(pCurrentNode, board); return true; } board[pCurrentNode->X()*yMax + pCurrentNode->Y()].setFillColor(sf::Color::Red); return false; }
void Transform(const std::string &from, const std::string &to, const HashSet &dict) { if (dict.count(from) && dict.count(to)) { std::queue<std::string> queue; std::map<std::string, std::string> back_track_map; queue.push(from); back_track_map[from] = ""; while (!queue.empty()) { std::string cur = queue.front(); queue.pop(); if (cur == to) { PrintPath(from, to, back_track_map); std::cout << std::endl; return; } else { for (int i = 0; i < cur.length(); i++) { for (char j = 'A'; j <= 'Z'; j++) { std::string new_word = cur; new_word.replace(i, 1, 1, j); if (dict.count(new_word) && !back_track_map.count(new_word)) { queue.push(new_word); back_track_map[new_word] = cur; } } } } } } std::cout << "There is no path from " << from << " to " << to << std::endl; }
void PrintPath(const std::string &from, const std::string &to, std::map<std::string, std::string> &back_track_map) { if (from != to) { PrintPath(from, back_track_map[to], back_track_map); std::cout << "->"; } std::cout << to; }
int main(int argumentCount, char **arguments) { i32 accuracy; _float collapseLen; Path *sourcePath; Path *destPath; if (argumentCount<2) return 0;//no arguments - exit accuracy = 0; collapseLen = 0; //check arguments for params for (i32 i=1;i<(argumentCount-1);i++) { //simple params, defined by first char switch(arguments[i][0]) { case 'a'://accuracy accuracy = atoi(arguments[i]+1); if (accuracy<0) accuracy=0; else if (accuracy>20) accuracy=20; break; case 'c'://collapse len collapseLen = atof(arguments[i]+1); if (collapseLen<0) collapseLen = 0; break; default://unknowns - ignore break; } } //create objects sourcePath = new Path(); destPath = new Path(); while(true) { //process data if (ParsePath(sourcePath,arguments[argumentCount-1])!=0) break; if (OrthogonalizePath(destPath,sourcePath,collapseLen)!=0) break; //print to output PrintPath(destPath,accuracy); break; } //free memory and exit delete sourcePath; delete destPath; return 0; }
/* 函数功能:输入一个整数和一颗二叉树,打印出二叉树中结点和为该整数的所有路径。 参数:二叉树根结点指针,一个整数 返回值:void */ void FindPath(BinarryTree* pTreeRoot, int nExpectedSum) { if(pTreeRoot==NULL) return; std::vector<int> path; int currentSum = 0; PrintPath(pTreeRoot, nExpectedSum, path, currentSum); }
/** * @brief 打印出query和text两个字符串的最长公共子子序列。 * @param query query的首指针 * @param query_len query的长度 * @param text_len text的长度 * @retval None * @see None * @note */ void PrintPath(char* query, int query_len, int text_len) { if(query_len == 0 || text_len == 0) return;//递归终止条件 if(LCSPath[query_len][text_len] == 0) { PrintPath(query, query_len - 1, text_len - 1); printf("%c", query[query_len - 1]); } else if(LCSPath[query_len][text_len] == 1) { PrintPath(query, query_len - 1, text_len); } else { PrintPath(query, query_len, text_len - 1); } }
int PrintPath(int *father, int root, int des) { if(father[des]!=root) { PrintPath(father,root,father[des]); printf("-%d",des); } else printf("%d-%d",root,des); return true; }
void PrintPath(long v) { if(par[v]==-1) { printf("%ld",v); return; } else { PrintPath(par[v]); printf(" %ld",v); } }
void main() { ReadInput(); path_vec shortestPath; //最短路径 int length = Dijkstra(shortestPath); paths.push_back(std::make_pair(length,shortestPath)); //找到最短路径 //PrintPath(shortestPath, length); for(unsigned int i=0; i<shortestPath.size()-1; i++) { path_vec path1; //去掉一条边以后的最短路径 memcpy(crt_map1, origin_map, sizeof(origin_map)); RemoveEdge(shortestPath[i], shortestPath[i+1]); //删除一条边以后找出最短路径 length = Dijkstra(path1); if(length==0) continue; paths.push_back(std::make_pair(length, path1)); //PrintPath(path1, length); for(unsigned int j=0; j<path1.size()-1; j++) { path_vec path2; //删除第二条边以后的最短路径 memcpy(crt_map2, crt_map1, sizeof(crt_map1)); RemoveEdge(path1[j], path1[j+1], crt_map2); length = Dijkstra(path2); if(length==0) continue; paths.push_back(std::make_pair(length, path2)); } } //将找到的路径排序,然后输出(会存在路径长度相同但是路线不同的路径) std::sort(paths.begin(), paths.end(), Compare); //删除重复的路径 RemoveDunplicated(paths); int outputCount = 0; for(paths_vec_iter iter = paths.begin(); iter != paths.end(); iter++) { if(outputCount++ > K) break; PrintPath(iter->second, iter->first); } }
Anneal::Path Anneal::FindPath(std::ostream &os) { std::uniform_real_distribution<double> distribution(0.0, 1.0); InitializeTemperature(); temperature_drop_times_ = 0; path_now_ = GenerateRandomPath(); value_now_ = Evaluate(path_now_); while (!ShouldTerminate()) { // a new t_ iterations_this_temperature_ = 0; while (!BalanceReached()) { iterations_this_temperature_++; Path neighbor = GenerateRandomNeighbor(path_now_); double new_value = Evaluate(neighbor); if (new_value <= value_now_ || distribution(generator_) < TransitionProbability(value_now_, new_value)) { path_now_ = neighbor; value_now_ = new_value; } } // balance reached at this temperature // print the path now PrintPath(std::cout); PrintPath(os); DropTemperature(); // counter updated inside } return path_now_; }
void AStar::Search() { AddNodeToOpenList(NULL, tRoot[iStartNode]); Node* pCurrentNode = NULL; while(!qOpenList.empty()) { pCurrentNode = VisitNode(); if (pCurrentNode == tRoot[iEndNode]) { PrintPath(pCurrentNode); break; } } }
void DFS() { int dir, IsFind, top = -1; struct path cur, next; cur.x = 0; cur.y = 0; cur.dir = -1; stack[++top] = cur; maze[0][0] = -1; while (top != -1) { cur = stack[top], dir = stack[top].dir; if (cur.x==4 && cur.y==4) { /* 表示已经找到出口,打印路径 */ PrintPath(top); break; }/* End of If */ IsFind = 0; while (dir<4 && IsFind==0) { /* 从上下左右4个方向分别探索 */ ++dir; next.x = cur.x + dx[dir]; next.y = cur.y + dy[dir]; if (IsInBound(next.x, next.y) && !maze[next.x][next.y]) { /* 可行位置 */ IsFind = 1; } }/* End of For */ if (IsFind) { next.dir = -1; stack[top].dir = dir; stack[++top] = next; maze[stack[top].x][stack[top].y] = -1; } else { maze[stack[top].x][stack[top].y] = 0; --top; } }/* End of While */ }/* DFS */
//BFS algorithm int shortestpath(Node *array, int Vnum, int root, int des) { int i,out,ss; //create a queue Queue *head=Initqueue(); Queue *path=Initqueue(); Node *travel,*p; int *color = (int *)malloc(Vnum*sizeof(int)); int *father = (int *)malloc(Vnum*sizeof(int)); for(i=0;i<Vnum;i++)father[i]=i; for(i=0;i<Vnum;i++)color[i]=white; //initialize colar Enqueue(head,root); color[root]=grey; father[root]=root; while(Isempty(head)!=1) { out = Dequeue(head); travel=array+out; for(p=travel->next;p!=NULL;p=p->next) { if(color[p->ID]==white) { Enqueue(head,p->ID); color[p->ID]=grey; father[p->ID]=out; } } color[out]=black; } if(color[des]==white) { printf("Error: there is no path between %d and %d.",root,des); ss=false; } else { //if there is a path, then print it out //for(i=0;i<Vnum;i++)printf("%d is father of %d\n",father[i],i); PrintPath(father,root,des); ss=true; } Clearqueue(head); Destroyqueue(head); free(color); free(father); return ss; }
menu_items_t printmenuSource(mxml_node_t *tree) { mxml_node_t *SourceNode=NULL; /*pointer to the Source node, topnode of this function*/ system("clear"); printf("Source\n------\n\n"); SourceNode = mxmlFindElement(tree, tree, /*Search from the top*/ "Source", NULL, NULL, /*The Source element*/ MXML_DESCEND); /*Descending*/ /*the search might return null*/ if ( SourceNode != NULL ) { /*search and handwalk */ printf("01) Sources:\n"); /*print all the Paths in the sources node*/ PrintPath(SourceNode,"Sources"); /*Now, lets search the User name********************************************/ printf("02) UserName: %s\n",getElemData(SourceNode,"UserName") ); /*Now, lets search the Password*******************************************/ printf("03) Password: %s\n",getElemData(SourceNode,"Password") ); /*Now, lets search the CharSet********************************************/ printf("04) CharSet: %s\n\n",getElemData(SourceNode,"CharSet") ); } else { /*No source node*/ /*print empty */ printf("01) Sources:\n" "*\t<n/a>\n\n" "02) UserName: <n/a>\n\n" "03) Password: <n/a>\n\n" "04) CharSet: <n/a>\n" "\n"); } return MENU_SOURCE; }
int main(int argc, const char * argv[]) { PathSegment *path = GenerateAdventure(); PrintPath(path); bool playing = true; char input[300]; int inputNumber; Player player; player.name = GetPlayerName(); Direction direction; while (playing) { PathSegment segment; player.health = 80; player.wealth = 100; player.currentPathSegment = path; printf("%s:Your health is %d\n, Your wealth is %d\n",player.name,player.health,player.wealth); printf("Please enter a direction: 0 for straight 1 for right and 2 for left\n"); scanf("%d",&direction); moveInDirection(&player, direction); printf("Your distance travelled is %d",player.distanceTraveled); if(player.health >= 100 || player.health <= 0) { printf("Game over"); break; } } FreeAllPathSegments(path); return 0; }
void tsp (int hops, int len, Path_t path, int *cuts) { int i ; int me, dist ; if (len >= minimum) { #ifdef DEBUG PrintPath("Too long path : ", hops, path); #endif (*cuts)++ ; return; } if (hops == NbCities) { #pragma omp critical if (len < minimum) { minimum = len ; // printf ("found path len = %3d :", len) ; // for (i=0; i < NbCities; i++) // printf ("%2d ", path[i]) ; // printf ("\n") ; } } else { me = path [hops-1] ; for (i=0; i < NbCities; i++) { if (!present (i, hops, path)) { path [hops] = i ; dist = distance[me][i] ; tsp (hops+1, len+dist, path, cuts) ; } } } }
// Helper recursively prints all paths through the ratings matrix, starting // at column col. static void PrintMatrixPaths(int col, int dim, const MATRIX& ratings, int length, const BLOB_CHOICE** blob_choices, const UNICHARSET& unicharset, const char *label, FILE *output_file) { for (int row = col; row < dim && row - col < ratings.bandwidth(); ++row) { if (ratings.get(col, row) != NOT_CLASSIFIED) { BLOB_CHOICE_IT bc_it(ratings.get(col, row)); for (bc_it.mark_cycle_pt(); !bc_it.cycled_list(); bc_it.forward()) { blob_choices[length] = bc_it.data(); if (row + 1 < dim) { PrintMatrixPaths(row + 1, dim, ratings, length + 1, blob_choices, unicharset, label, output_file); } else { PrintPath(length + 1, blob_choices, unicharset, label, output_file); } } } } }
int main() { char *query = (char*)malloc(sizeof(char)*MAXNUM); char *text = (char*)malloc(sizeof(char)*MAXNUM); printf("请输入query:"); gets(query); printf("请输入text:"); gets(text); //char query[] = "ABCBDAB"; //char text[] = "BDCABA"; int query_len = 0, text_len = 0, i, j; while(query[query_len] != '\0'){query_len++;}; while(text[text_len] != '\0'){text_len++;}; LCS(query, query_len, text, text_len); printf("LCS长度为%d\r\n",LCSPro[query_len][text_len]); printf("LCS为"); PrintPath(query, query_len, text_len); free(query); free(text); }
AWaypoint* AProtherer::NextWaypointTowards(AWaypoint* destination) { FString* text = NULL; if (CurrentLocation == destination) { return destination; } /* text = new FString("Finding path from "); text->Append(CurrentLocation->Name); text->Append(" to "); text->Append(destination->Name); sayDialog(text); */ // 1. Get the shortest path from CurrentLocation to destination.. TArray<AWaypoint*> emptyList; TArray<AWaypoint*> shortestPath = GetShortestPathBetween(CurrentLocation, destination, emptyList); // If there is a shortest path, return the frst element from it!. if (shortestPath.Num() > 1) { //sayDialog(new FString("Found Shortest Path! Here it is:")); PrintPath(shortestPath); text = new FString("Going to the first node of the shortest path "); text->Append(shortestPath[1]->Name); sayDialog(text); return shortestPath[1]; } // If there is no shortest path from CurrentLocation to Destination (which should not happen!) // then return null. sayDialog(new FString("Error Condition: No Path found!")); return NULL; }
int main() { long vert,edge,start,i; while(scanf("%ld%ld",&vert,&edge)==2) { Take_input(vert,edge,true); scanf("%ld",&start); DJ(start,vert); for(i=1;i<=vert;i++) { printf("path from %ld to %ld :\n",start,i); PrintPath(i); printf("\ncost : %ld \n\n",cost[i]); } } return 0; }
/// Saves map data to file. bool Map::Save(const char * filename){ std::fstream file; file.open(filename, std::ios_base::out | std::ios_base::binary); /// If failed to open, close and return false. if (!file.is_open()){ file.close(); std::cout<<"\nERROR: Unable to open filestream to "; PrintPath(filename); lastErrorString = "Unable to open file stream."; return false; } /// Set version to latest header.version = MV_LATEST; header.dateCreated = time(0); // Get current time strcpy(header.mapName, name); // Set header map name to the one we're using in the editor /// Verify that header is OK before we save it! if (!VerifyHeader()){ std::cout<<"\nERROR: Unsupported map version. Try updating the game! ^^"; return false; } int size = sizeof(MapFileHeader); // Should be int(4) + long(4) + 260 chars header.Write(file); /// Make sure, // NO! this is check in the WriteEntities() function! // assert(cEntities.Size() == entities.Size()); /// Block types for writing int blockType = -1; // Write entities if we have any if (NumEntities() > 0 && NumEntities() <= MAX_ENTITIES){ WriteEntities(file); } else{ std::cout<<"\nInvalid amount of entities: "<<NumEntities(); lastErrorString = "No entities to save."; return false; } /// Write paths block if we got any if (paths.Size() > 0){ WritePaths(file); } int end = BLOCK_END_OF_FILE; if (header.version < MV_PATHS) end = OLD_BLOCK_END_OF_FILE; file.write((char*)&end, sizeof(int)); int endNull = 0; file.write((char*)&endNull, sizeof(int)); file.close(); /// Consider using other mechanisms to check that everything was written correctly... ////////////////////////////////////////// // Check that the written contents are the same as what we wanted to save.. if (false){ file.open(filename, std::ios_base::in | std::ios_base::binary); Map verificationMap; file.read((char*) &verificationMap.header, sizeof(MapFileHeader)); // Check stuff bool verificationDone = false; while(!verificationDone){ int blockType; file.read((char*) &blockType, sizeof(int)); int blockSize; file.read((char*) &blockSize, sizeof(int)); switch(blockType){ case BLOCK_ENTITIES: verificationMap.ReadEntities(file); break; case OLD_BLOCK_END_OF_FILE: verificationDone = true; std::cout<<"\nVerification done! File is as it should be."; break; default: std::cout<<"\nUnknown block type! You failed douche!"; assert(false && "Unknown block type when verifying saved file!"); break; } } file.close(); } return true; }
int main(int argc, char **argv) { int i = 0, j; int end_flag = -1; static int count = 0; geometry_msgs::PoseStamped posestamped; nav_msgs::GetMap getmap; ros::init(argc, argv, "astar_navi"); ros::NodeHandle n; ros::Subscriber map_sub = n.subscribe("/map", 1000, mapCallback); ros::Subscriber goal_sub = n.subscribe("/move_base_simple/goal", 1000, GoalCallback); ros::Subscriber start_sub = n.subscribe("/initialpose", 1000, StartCallback); ros::Publisher lane_pub = n.advertise<nav_msgs::Path>("lane_waypoint", 1000, true); ros::Publisher ruled_pub = n.advertise<waypoint_follower::lane>("traffic_waypoint", 1000, true); ros::Publisher pose_pub = n.advertise<geometry_msgs::PoseArray>("poses", 1000, true); ros::Publisher start_pub = n.advertise<geometry_msgs::PoseStamped>("start_pose", 1000, true); ros::Publisher footprint_pub = n.advertise<geometry_msgs::PolygonStamped>("car_footprint", 1000, true); ros::ServiceClient getmap_srv_ = n.serviceClient<nav_msgs::GetMap>("/static_map"); plan_poses.header.frame_id = PATH_FRAME;//for debug ros::Rate loop_rate(LOOP_RATE); while (ros::ok()){ ros::spinOnce(); if (_map_set == false || _goal_set == false || _start_set == false) { std::cout << "\rtopic waiting \rtopic waiting"; for (j = 0; j < i; j++) {std::cout << ".";} i++; i = i%10; std::cout << std::flush; loop_rate.sleep(); continue; } /*******for debug***********/ /* sx = 58; sy = 128; dstheta = 0.000; stheta = 0; map[sy][sx][stheta].x = 5.899; map[sy][sx][stheta].y = 12.898; map[sy][sx][stheta].theta = 0.00; */ /***************************/ /* Atar search loop */ while(1){ count++; end_flag = AStar(); if (!(count%1000) || count < 1000){ pose_pub.publish(plan_poses);//for visualization } if (!end_flag){ std::cout << "GOAL!!" << std::endl; PrintPath(); lane_pub.publish(plan_path); ruled_pub.publish(ruled_waypoint); pose_pub.publish(plan_poses); Carfootprint(); _start_set = false; _goal_set = false; _map_set = false; /* reset map data */ InitData(); getmap_srv_.call(getmap); mapReset(getmap.response.map); break; } else if (end_flag == 1){ std::cout << "FAILED..." << std::endl; _start_set = false; _goal_set = false; _map_set = false; /* reset map data */ InitData(); getmap_srv_.call(getmap); mapReset(getmap.response.map); break; } else { continue; } } } return 0; }
int main(){ /* int a,b,c,d,e,f,g,h; scanf("%d,%d,%d,%d",&a,&b,&c,&d); getchar(); Queue Q = CreateQueue(); Enqueue(Q,a); Enqueue(Q,b); Enqueue(Q,c); Enqueue(Q,d); e = Dequeue(Q); printf("%d\n",e); f = Dequeue(Q); printf("%d\n",f); g = Dequeue(Q); printf("%d\n",g); h = Dequeue(Q); printf("%d\n",h); printf("%d,%d,%d,%d\n",e,f,g,h); getchar(); */ int vertexNumber = 0; int vertex; int weights; int i; int f; Table table; printf("Create graph:\n"); printf("Input vertex number:"); scanf("%d",&vertexNumber); getchar(); printf("Graph initing...\n"); Graph graph = CreateGraph(vertexNumber); if(graph == NULL){ printf("Graph init failed\n"); return 0; } for(i = 1;i <= vertexNumber;i++){ printf("Vertex:%d\nHas adjavent?[1/0]:",i); scanf("%d",&f); getchar(); while(f){ printf("adjacent:"); scanf("%d",&vertex); getchar(); printf("weights:"); scanf("%d",&weights); getchar(); printf("continue?[1/0]:"); scanf("%d",&f); getchar(); AddEdge(graph,i,vertex,weights); } } ShowGraph(graph,vertexNumber); printf("input source:"); scanf("%d",&i); getchar(); table = Dijkstra(graph,i,vertexNumber); ShowTable(table,vertexNumber); PrintPath(table,i,2); printf("hello linux c\n"); return 0; }
/// Loads map data from file. bool Map::Load(const char * fromFile){ std::cout<<"\nLoading map from file: "<<fromFile; std::fstream file; file.open(fromFile, std::ios_base::in | std::ios_base::binary); /// If failed to open, close and return false. if (!file.is_open()){ file.close(); std::cout<<"\nERROR: Unable to open filestream to "; lastErrorString = "Unable to open filestream."; PrintPath(fromFile); return false; } /// Read and verify header before reading any more header.Read(file); if (!VerifyHeader()){ std::cout<<"\nERROR: Unsupported map version. Try updating the game! ^^"; return false; } bool endOfFile = false; while (!file.eof() && !endOfFile){ /// Read next integer to inrepret type of next data block int type; int blockSize; file.read((char*) &type, sizeof(int)); if (header.version < MV_PATHS) file.read((char*) &blockSize, sizeof(int)); if (type < 0 || type > MAX_BLOCK_TYPES){ SWAPFOUR(type); } switch(type){ case BLOCK_ENTITIES: ReadEntities(file); break; case BLOCK_PATHS: ReadPaths(file); break; case OLD_BLOCK_END_OF_FILE: { /// Check version here. if (header.version < MV_PATHS){ endOfFile = true; break; } break; } case BLOCK_END_OF_FILE: endOfFile = true; break; default: std::cout<<"\nUnknown block type: "<<type; std::cout<<"\nAborting loading procedure because of unknown data in stream."; file.close(); return false; } } /// Close file ^^ file.close(); source = fromFile; mapDataOK = true; std::cout<<"\nFile successfully read."; return true; }
//寻找路径 int FindPath(int x,int y) { int dir=0; //初始方向(0:向下;1:向右;2:向上;3:向左) int flag=0; //标记是否存在通路 if(x==1 && y==1) //如果为起点 { Push(1,1); //压栈 maze[1][1]=1; //标记为已走过 } if(x==H_NUM-2 && y==V_NUM-2) //到达终点 { PrintPath(); //输出路径 Pop(); //终点出栈 return 0; //到达终点,停止扫描 } else { while(dir<4) { switch(dir) { case 0: { if(maze[x+1][y]==0) { flag=1; Push(x+1,y); //将有通路的坐标点压栈 maze[x+1][y]=1; //标记当前点已走过 if(!FindPath(x+1,y)) //递归,若此方向上无法找到通路,则flag=0 flag=0; } } break; case 1: { if(maze[x][y+1]==0) { flag=1; Push(x,y+1); maze[x][y+1]=1; if(!FindPath(x,y+1)) flag=0; } } break; case 2: { if(maze[x-1][y]==0) { flag=1; Push(x-1,y); maze[x-1][y]=1; if(!FindPath(x-1,y)) flag=0; } } break; case 3: { if(maze[x][y-1]==0) { flag=1; Push(x,y-1); maze[x][y-1]=1; if(!FindPath(x,y-1)) flag=0; } } break; } dir++; //下一个方向 } if(!flag) //当前坐标点周围无通路 { Pop(); //将当前坐标点出栈 return 0; } } return 1; }