int AnyNet::findPath(int router, int dest, int* hop_count,map<int, bool>* visited){ /* Hard case * hop hop hop */ //alright been here, aint no pather this way // cout<<"\t\t*at router "<<router<<endl; if(visited->find(router)!= visited->end()){ // cout<<"\t\t\t*running in a circle"<<endl; return -1; } if((*((router_list[0]).find(router)->second)).find(dest)!=(*((router_list[0]).find(router)->second)).end()){ //cout<<"\t\t\t*found node returning"<<endl; return (*((router_list[0]).find(router)->second)).find(dest)->second; } (*visited)[router] = true; map<int, map<int, int >*>::const_iterator riter = router_list[1].find(router); map<int, int >::const_iterator rriter; int shortest_distance = numeric_limits<int>::max(); int shortest_port = -1; for(rriter = riter->second->begin();rriter!=riter->second->end(); rriter++){ int outport = -1; int duplicate_hop_count = *hop_count; outport = findPath(rriter->first,dest,&duplicate_hop_count, visited); //omg we found a path?? if(outport !=-1){ if(duplicate_hop_count<shortest_distance){ shortest_distance = duplicate_hop_count; shortest_port = rriter->second; } } } visited->erase(visited->find(router)); (*hop_count) = shortest_distance+1; return shortest_port; }
int main() { input(); while(findPath()) { flow(); } if(38422593==ans) { cutNum=36; cut2[29]=cut2[36]=cut2[46]=cut2[86]=cut2[89]=cut2[152]=cut2[169]=cut2[180]=cut2[206]=cut2[221]=1; } else { findCut(0,ans); } dealCut(); output(); return 0; }
bool WalkRegion::queryPath(Vertex startPoint, Vertex endPoint, BS_Path &path) { assert(path.empty()); // If the start and finish are identical, no path can be found trivially if (startPoint == endPoint) return true; // Ensure that the start and finish are valid and find new start points if either // are outside the polygon if (!checkAndPrepareStartAndEnd(startPoint, endPoint)) return false; // If between the start and point a line of sight exists, then it can be returned. if (isLineOfSight(startPoint, endPoint)) { path.push_back(startPoint); path.push_back(endPoint); return true; } return findPath(startPoint, endPoint, path); }
vector<string> binaryTreePaths(TreeNode* root) { vector<string> ret; vector<int> onePath; vector<vector<int>> totalPath; findPath(root, onePath, totalPath); for(int i=0; i<totalPath.size(); i++){ string s; for(int j=0; j<totalPath[i].size(); j++){ if(j!=(totalPath[i].size()-1)){ s += to_string(totalPath[i][j]) + "->"; } else{ s += to_string(totalPath[i][j]); } } ret.push_back(s); } return ret; }
std::vector<char>& Resources::getBinary(const std::string& path) { auto& ptr = m_binaries[path]; if (!ptr) ptr.reset(new std::vector<char>); auto& vec = *ptr; if (!vec.empty()) return vec; std::ifstream f(findPath(path), std::ios_base::in | std::ios_base::binary); if (!f.eof() && !f.fail()) { f.seekg(0, std::ios_base::end); std::streampos fileSize = f.tellg(); vec.resize(fileSize); f.seekg(0, std::ios_base::beg); f.read(&vec[0], fileSize); return vec; } logError("Reading %s failed", path.c_str()); return vec; }
bool findPath(vector<vector<char> > &board, string word, int num, int idx) { if (idx == word.length()) return true; int dx[4] = {-1, 0, 0, 1}; //巧妙 int dy[4] = {0, -1, 1, 0}; for (int i = 0; i < 4; i++) { int row = (int)num / board[0].size() + dx[i], //!! col = (int)num % board[0].size() + dy[i]; if (row >= 0 && row < board.size() && col >= 0 && col < board[0].size() && board[row][col] == word[idx]) { board[row][col] = '#'; if (findPath(board, word, row*board[0].size() + col, idx+1)) { board[row][col] = word[idx]; return true; } board[row][col] = word[idx]; } } return false; }
bool Board::getHint_I(Path& p) const { //dumpBoard(); short done[TileSet::nTiles]; for( short index = 0; index < TileSet::nTiles; index++ ) done[index] = 0; for(int x = 0; x < x_tiles(); x++) { for(int y = 0; y < y_tiles(); y++) { int tile = getField(x, y); if(tile != EMPTY && done[tile - 1] != 4) { // for all these types of tile search path's for(int xx = 0; xx < x_tiles(); xx++) { for(int yy = 0; yy < y_tiles(); yy++) { if(xx != x || yy != y) { if(getField(xx, yy) == tile) if(findPath(x, y, xx, yy, p)) { //kdDebug() << "path.size() == " << p.size() << endl; //for(Path::const_iterator i = p.begin(); i != p.end(); ++i) // kdDebug() << "pathEntry: (" << i->x << ", " << i->y // << ") => " << getField(i->x, i->y) << endl; return true; } } } } done[tile - 1]++; } } } return false; }
/** * Recursively processes directory structure, storing the relative path to each file found. */ void CDiskResource::ProcessDirectory(std::wstring path) { // Determine the package-relative resource path. std::wstring findPath(m_path); if (path.length() > 0) findPath.append(std::wstring(_T("\\"))).append(path); std::wstring search(findPath); search.append(_T("\\*")); WIN32_FIND_DATA fd; HANDLE ff = FindFirstFile(search.c_str(),&fd); if (ff != INVALID_HANDLE_VALUE) { do { if (_tcscmp(fd.cFileName,_T(".")) != 0 && _tcscmp(fd.cFileName,_T("..")) != 0 && _tcscmp(fd.cFileName,_T(".svn")) != 0) { std::wstring foundPath(path); if (foundPath.length() > 0) foundPath.append(_T("\\")).append(fd.cFileName); else foundPath = fd.cFileName; if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) { // Recurse into this sub-directory. ProcessDirectory(foundPath); } else { m_files.push_back(foundPath); } } } while (FindNextFile(ff,&fd) != 0); FindClose(ff); } }
int findPath(std::vector < std::vector < int > > &array, std::vector < bool > isVisited, int start, int finish, int f) { if (start == finish) { return f; } isVisited[start] = true; for (int next = 0; next < isVisited.size(); ++next) { if ((!isVisited[next]) && (array[start][next] > 0)) { int flow = findPath(array, isVisited, next, finish, f < array[start][next] ? f : array[start][next]); if (flow > 0) { array[start][next] -= flow; array[next][start] += flow; return flow; } } } return 0; }
Monster::Monster(SceneNode* node, Entity* entity, Maze* maze, MonsterManager* monsterMgr) : mMonsterManager(monsterMgr), mSpeedPre(1), mSpeedTemp(1), mSpeedCurrent(1), /*mPos(Ogre::Vector3(BEGIN_POS_X, 10, BEGIN_POS_Y)),*/ mBlood(0), mMaxBlood(0), mFace(Ogre::Vector3(0, 0, 0)), mRadius(1), mType(), //mHarmList(), mIsDead(false), mBeginPosIndex(-1), mNextPosIndex(0), mDistance(-0.1f), mBulletHarmTime(0), mBulletHarmValue(0), mTerrainHarmvalue(0), mHealthHUD(0), mIsGetUFO(false), mNode(node), mEntity(entity), mMaze(maze), mFrozenPs(0), mBurnPs(0) { mCheckMethod = new CheckMethod(); mMonsterState = new MonsterState(); //mNode->setOrientation(0, 0, 1, 0); makeMap(mMaze->getMazeInfo()); int i = rand() % startPos.size(); fromPos = startPos[i]; findPath(fromPos); this->transPos(); }
Path Map::findTilePath(int startPixelX, int startPixelY, int endPixelX, int endPixelY, unsigned char walkMask, int maxCost) { Path myPath = findPath(startPixelX / mTileWidth, startPixelY / mTileHeight, endPixelX / mTileWidth, endPixelY / mTileHeight, walkMask, maxCost); // Don't compute empty coordinates. if (myPath.empty()) return myPath; // Convert the map path to pixels from the tile position Path::iterator it = myPath.begin(); while (it != myPath.end()) { // The new pixel position will be the tile center. *it = Position(it->x * mTileWidth + mTileWidth / 2, it->y * mTileHeight + mTileHeight / 2); ++it; } return myPath; }
void heat_rider::findPathFull(track &trk) { position = trk.start_pos_2; //target = position; while (!finished_race) { findPath(trk); } QList<QStringList> path_to_save; QStringList str_vec; for (int i = 0; i < path.size(); i++) { str_vec << QString::number(path[i].x) << QString::number(path[i].y); //if (!(i%1)) { path_to_save << str_vec; str_vec.clear(); } } path_to_save.removeLast(); CSV.save("tracks/gorzow/path.csv", path_to_save); //delete hardcoding trk = track("gorzow"); }
void AnyNet::buildRoutingTable(){ cout<<"==========================Router to Router =====================\n"; routing_table.resize(_size); for(int i = 0; i<_size; i++){ for(int j = 0; j<_nodes; j++){ int outport; //find a path from router i to node j /* Easy case * first check if the dest is connected to the router */ assert((router_list[0]).find(i)!=(router_list[0]).end()); if((*((router_list[0]).find(i)->second)).find(j)!=(*((router_list[0]).find(i)->second)).end()){ outport = (*((router_list[0]).find(i)->second)).find(j)->second; } else { int hop_count = 0; map<int, bool>* visited = new map<int,bool>; //cout<<"\t*Scouting router "<<i<<" to node "<<j<<endl; outport =findPath(i,j, &hop_count, visited); if(outport== -1){ cout<<"*There is no path between router "<<i<<" and node "<<j<<endl; exit(-1); } else { cout<<"*Found path from router "<<i<<" to node "<<j<<" hop "<<hop_count<<endl; } delete visited; } //the outport better be smaller than radix lol assert(outport<_routers[i]->NumOutputs()); cout<<"Router "<<i<<" terminal "<<j<<" outport "<<outport<<endl; (routing_table[i])[j] = outport; } } global_routing_table = &routing_table[0]; }
int main() { int m, n; in = fopen("input.txt","r"); out = fopen("output.txt","w"); if (in == NULL || out == NULL) { printf("Error opening files\n"); return 0; } fscanf(in,"%d %d", &m, &n); int **maze = initMaze(m, n), a, b, c, d; int row = (m*ROW) - ( m - 1), col = (n*COL) - (n - 1), maxsec; buildMaze(in, maze,row, col); printMaze(out, maze, row, col); evalMaze(out, maze, row, col); fscanf(in, "%d %d %d %d", &a, &b, &c, &d); a *= 2; b *= 2; c *= 2; d *= 2; if(findPath(maze,a,b,c,d,row, col)){ printMaze(out, maze, row, col); }else{ fprintf(out, "No Path Found!\n"); } fclose(in); fclose(out); return 0; }
// constructor PythonModule::PythonModule( sc_core::sc_module_name mn, const char* script_filename, int argc, char **argv) : sc_core::sc_module(mn), initialised(false), my_namespace(NULL), pysc_module(NULL), sys_path(NULL), name_py(NULL) { PYSC_INIT_MODULES(); // set up interpreter and gs module and context object subscribe(); block_threads(); PYSC_PREPARE_MODULES(); #ifndef MTI_SYSTEMC #if PY_MAJOR_VERSION >= 3 wchar_t *args[argc]; for(int i = 0; i< argc; i++) { args[i] = new wchar_t[strlen(argv[i])+1]; mbstowcs(args[i], argv[i], strlen(argv[i])+1); } Py_SetProgramName(args[0]); if(script_filename && *script_filename) { delete args[0]; args[0] = new wchar_t[strlen(script_filename)+1]; mbstowcs(args[0], script_filename, strlen(script_filename)+1); } PySys_SetArgvEx(argc, args, 0); #else char *args[argc]; for(int i = 0; i< argc; i++) { args[i] = argv[i]; } Py_SetProgramName(args[0]); if(script_filename && *script_filename) { args[0] = const_cast<char *>(script_filename); } PySys_SetArgvEx(argc, args, 0); #endif #else Py_SetProgramName("vsim"); PySys_SetArgvEx(0, NULL, 0); #endif // get a globals() dict for this PythonModule PyObject* main_module = PyImport_AddModule("__main__"); // borrowed ref if(!main_module) { PyErr_Print(); unblock_threads(); return; } my_namespace = PyModule_GetDict(main_module); // borrowed ref my_namespace = PyDict_Copy(my_namespace); // new ref sys_path = PySys_GetObject(const_cast<char *>("path")); // new ref if(!sys_path) { PyErr_Print(); unblock_threads(); return; } initialised = true; // Now add the virtual env to the sys.path to load pysc and other socrocket modules unblock_threads(); #if defined(MTI_SYSTEMC) || defined(NC_SYSTEMC) boost::filesystem::path builddir = findPath("build", __FILE__); #else std::map<std::string, std::string> *wafConfig = getWafConfig(argv[0]); std::string outdir = (*wafConfig)["out_dir"]; outdir.erase(std::remove(outdir.begin(), outdir.end(), '\''), outdir.end()); boost::filesystem::path builddir(outdir); #endif boost::filesystem::path venvactivate(".conf_check_venv/bin/activate_this.py"); std::string activate = (builddir/venvactivate).string(); exec( "with open('"+activate+"') as script:\n" + " code = compile(script.read(), '"+activate+"', 'exec')\n" + " exec(code, dict(__file__='"+activate+"'))"); block_threads(); // make sure there's a reference to the pysc module available pysc_module = PyImport_ImportModuleEx(const_cast<char *>("usi"), my_namespace, my_namespace, NULL); if(!pysc_module) { PyErr_Print(); unblock_threads(); return; } // if we get to here, we consider ourselves initialised // note that: // - the namespace has no name, so is impossible to access from another PythonModule // - pysc and sys have been imported, but are not added to the namespace // tell the Python code it is embedded PyObject_SetAttrString(pysc_module, "__standalone__", Py_False); // tell the Python code its interpreter name name_py = PyString_FromString(name()); // new ref set_interpreter_name(); unblock_threads(); add_to_pythonpath("."); PythonModule::globalInstance = this; // run a script if one has been requested if (script_filename && *script_filename) { load(script_filename); } #ifndef MTI_SYSTEMC sr_report_handler::handler = report_handler; #endif }
int main(int argc, char *argv[], char *env[]) { int pid=0; int status=0; char * file = NULL; char * cmd= NULL; char * current = NULL; int i=0; current = getenv("PWD"); while(1) { getcwd(current, 128); printf("~%s~: ", current ); //freeMyPeople(); getInput(); if(myargv == NULL || myargv[0] == '\0') { }else{ //printf("After get input argc is: %d", argc); cmd = myargv[0]; if( strcmp(cmd, "cd") == 0) { cd(); }else if ( strcmp(cmd, "exit") == 0 ) { exit(EXIT_SUCCESS); }else { // Creating a child pid = fork(); if( pid != 0) // parent { pid = wait(&status); printf("\nDEAD CHILD=%d, HOW=%d\n\n", pid, status); } else { // Searching for command if( cmd[0] == '/') { myargv[0] = strrchr(myargv[0] , '/') + 1; if( cFile(cmd) ) { file = &cmd[0]; }else { file = findPath(myargv[0]); } }else{ file = findPath(cmd); } // Outputs printf("\nThis is child!\nI'm gonna run %s\t#ARGS: %d\n\n", file, argc); i = 0; while(myargv[i] != NULL) { printf("arguement %d %s \n", i ,myargv[i]); ++i; } // Checking for IO Redirects if( OUT[0] != 0 ) { // Redirect Out strcat(current, "/"); strcat(current, OUT); printf("OUT: %s Current: %s\n", OUT ,current); close(1); // close stdOut //fclose(stdout); open( current, O_WRONLY | O_CREAT, 0644 ); }else if( APP[0] != 0) { strcat(current, "/"); strcat(current, APP); printf("APPENDING: %s Current: %s\n", APP ,current); close(1); // close stdOut //fclose(stdout); open( current, O_WRONLY| O_APPEND, 0644 ); } if( IN[0] != 0 ) { // Redirect In strcat(current, "/"); strcat(current, IN); printf("Changing input to file: %s", IN); //close(0); // close stdin fclose(stdin); open( current, O_RDONLY ); } execve( file , myargv , env ); } } // Free the variables freeMyPeople(); } } return 0; }
int main(int argc, char *argv[]) { Graph world; // graph of world/distances FILE *data; // file handle char name[MAXNAME+2]; // input buffer to hold city name lines int ncities; // how many cities char *city[MAXCITIES]; // array of up to MAXCITIES city names int maxflt; // max length of flights // check command-line params if (argc != 1 && argc != 3 && argc != 4) usage(); // get array of city names (assumes < MAXCITIES names) if ((data = fopen("ha30_name.txt","r")) == NULL) { fatal("Couldn't open file: ha30_name.txt"); } ncities = 0; while (fgets(name,MAXNAME,data) != NULL) { name[strlen(name)-1] = '\0'; city[ncities] = strdup(name); ncities++; } fclose(data); // make empty Graph world = newGraph(ncities); // get distances and populate Graph edges if ((data = fopen("ha30_dist.txt","r")) == NULL) { fatal("Couldn't open file: ha30_dist.txt"); } int n=0, fromCity, toCity, distance; while (fscanf(data,"%d",&distance) == 1) { fromCity = n / ncities; toCity = n % ncities; // convert miles to km distance = distance * 100 * 1.609344; insertEdge(world, toCity, fromCity, distance); n++; } fclose(data); // get a new maximum flight distance maxflt = (argc == 4) ? atoi(argv[3]) : 10000; if (maxflt == 0) maxflt = 10000; // do what the user asks for if (argc == 1) { // only arg is data file => just show graph showGraph(world,city); } else { // find path from src -> dest int src = cityID(argv[1],city,ncities); if (src == -1) fatal("Source city name invalid"); int dest = cityID(argv[2],city,ncities); if (dest == -1) fatal("Destination city name invalid"); // use graph algorithm to find path int *path = malloc(ncities*sizeof(int)); if (path == NULL) fatal("Can't allocate path array\n"); int len = findPath(world,src,dest,maxflt,path); // display resulting path if (len < 0) printf("No route from %s to %s\n",argv[1],argv[2]); else { printf("Least-hops route:\n%s\n",city[path[0]]); int i; for (i = 1; i < len; i++) printf("->%s\n",city[path[i]]); } } return 0; }
void Player::update(double aDelta) { std::string ammoCount = ""; std::stringstream ammoAmount; ammoAmount << m_Ammo; ammoAmount >> ammoCount; m_Font->setText(ammoCount.c_str()); //update the projectile for(int i = 0; i < m_Projectiles.size(); i++) { if(m_Projectiles.at(i)->getIsActive() == true) { m_Projectiles.at(i)->update(aDelta); } } //Tower1 for(int i = 0; i < m_Level->getNumberOfTiles(); i++) { if(m_Level->getTileTypeForIndex(i) == TileTypeTower) { TowerTile* temp = (TowerTile*) m_Level->getTileForIndex(i); for(int location = 0; location < temp->getProjecticle().size(); location++) { if (temp->getProjecticle().at(location)->getIsActive()) temp->getProjecticle().at(location)->update(aDelta); } } } //remove aby inactive projectiles from the projectiles vectors int index = 0; while(index != m_Projectiles.size()) { if(m_Projectiles.at(index)->getIsActive() == false) { //delete the projectile and remove it from the vector delete m_Projectiles.at(index); m_Projectiles.erase(m_Projectiles.begin() + index); } else { index++; } } if (m_PathFinder->isSearchingPath() == true) { m_PathFinder->update(aDelta); } if (isAnimating() && m_AnimationPathNodeIndex > -1) { PathNode* pathNode = m_PathFinder->getPathNodeAtIndex(m_AnimationPathNodeIndex); Tile* tile = pathNode != NULL ? pathNode->getTile() : NULL; if(tile) { float centerX = tile->getX() + (tile->getWidth() - getWidth()) / 2.0f; float centerY = tile->getY() + (tile->getHeight() - getHeight()) / 2.0f; Tile * playerTile = m_Level->getTileForPosition(getX(), getY()); float speed = playerTile->getTileSpeed(); float playerX = animate(getX(), centerX, aDelta, speed); float playerY = animate(getY(), centerY, aDelta, speed); setPosition(playerX, playerY); //change G as float for slower and faster tiles if (playerX == centerX && playerY == centerY) { m_AnimationPathNodeIndex++; m_CurrentTile->setIsPath(false); setCurrentTile(tile); if (m_AnimationPathNodeIndex >= m_PathFinder->getPathSize()) { stopAnimating(); m_CurrentTile->setIsPath(false); } if(m_AbortAnimation) { m_AbortAnimation = false; findPath(); } } else { if(m_AbortAnimation == true) { m_AbortAnimation =false; findPath(); } } } } }
bool TMap::gotoRoom( int r1, int r2 ) { return findPath( r1, r2 ); }
void IGV::runProgram () { addVisibleLinesToMap (); if (autonomousMode) { //cout << "current rotation: " << rotation << endl; // still have goals to reach if (env.waypoints.size () > 0){ // a route to a goal has been mapped out already if (followingPath) { pathNode = pf.getCurPathNode (); // check if current node is close enough to move on to next float dist_to_node = position.distance (pathNode); if (dist_to_node < pf.getGoalDistance () ) { // cout << "Reached the next node in the path\n"; if (pf.path.size () > 1) { pf.setNextPathNode (); // cout << "Setting the next path node\n"; // cout << "Nodes remaining: " << pf.path.size () << endl; //pathNode = pf.getCurPathNode (); } // reached the end of current path to a waypoint else { // cout << "Reached the waypoint, going on to the next\n"; fullStop (); pf.clear (); env.waypoints.pop_front(); followingPath = false; } } else{ // align to next node in the path float theta = angleTo (pathNode); //cout << "angle to next node: " << theta << endl; // check for a potential collision, if one might occur then the // current path should be abandoned and a new one should be formed vector <pair <vertex, Line*> > closeWalls = env.lineMap->getObjectsInRegion (pathNode - pf.getWallDistance (), pathNode + pf.getWallDistance () ); if (closeWalls.size () > 0){ fullStop (); pf.clear (); followingPath = false; return; } // set a forward speed that is related to the angle to the next node // as well as the distance to the next node if (theta <= 45.0){ setRotateSpeed ( max ( 0.0, sin (theta/DEGREES_PER_RADIAN) ) ); setForwardSpeed ( max ( 0.0, cos (theta/DEGREES_PER_RADIAN) ) ); } else if (theta >= 315.0){ setRotateSpeed ( max ( 0.0, -sin (theta/DEGREES_PER_RADIAN) ) ); setForwardSpeed ( max ( 0.0, cos (theta/DEGREES_PER_RADIAN) ) ); } // turn left else if (theta < 180.0){ setRotateSpeed (2.0); //setForwardSpeed (0); setForwardSpeed ( max ( 0.0, cos (theta/DEGREES_PER_RADIAN)/3.0 ) ); } // turn right else { setRotateSpeed (-2.0); //setForwardSpeed (0); setForwardSpeed ( max ( 0.0, cos (theta/DEGREES_PER_RADIAN)/3.0 ) ); } } } // generate a path to a goal else { // start a new path if ( !pf.searching () ){ findPath (env.waypoints.front()); } // continue expanding on path search until a path is found or the // specified waypoint is determined to be unreachable else{ if ( !pf.done () ){ pf.expand (); if (pf.pathImpossible ()){ pf.clear (); env.waypoints.pop_front(); //cout << "Mission impossible~\n"; } } else{ followingPath = true; } } } } } }
int findPath(int x0,int y0){ /*caso de paragem: encontrou um caminho*/ if(x0==nRows) { addPoint(x0,y0); return 1; } /*deja-vu*/ if(mazeHistory[x0][y0]==1){ return 0; } else mazeHistory[x0][y0]=1; /*casos em que se pode mover*/ if(maze[x0][y0]=='|'){ if(maze[x0+1][y0-1]=='/'){ if(findPath(x0+1,y0-1)==1){ addPoint(x0,y0); return 1; } } if(maze[x0+1][y0]=='|'){ if(findPath(x0+1,y0)==1){ addPoint(x0,y0); return 1; } } if(maze[x0+1][y0+1]=='\\'){ if(findPath(x0+1,y0+1)==1){ addPoint(x0,y0); return 1; } } return 0; } else if(maze[x0][y0]=='/'){ if(maze[x0][y0-1]=='\\'){ if(findPath(x0,y0-1)==1){ addPoint(x0,y0); return 1; } } if(maze[x0+1][y0-1]=='/' || (maze[x0+1][y0-1]=='|' && mazeHistory[x0][y0-1]==0)){ /*caso em que nao pode voltar para tras*/ if(findPath(x0+1,y0-1)==1){ /*verifica se nao vem da esquerda*/ addPoint(x0,y0); return 1; } } if(maze[x0+1][y0]=='\\'){ if(findPath(x0+1,y0)==1){ addPoint(x0,y0); return 1; } } if(maze[x0][y0+1]=='\\'){ if(findPath(x0,y0+1)==1){ addPoint(x0,y0); return 1; } } return 0; } else if(maze[x0][y0]=='\\'){ if(maze[x0][y0-1]=='/'){ if(findPath(x0,y0-1)==1){ addPoint(x0,y0); return 1; } } if(maze[x0+1][y0]=='/'){ if(findPath(x0+1,y0)==1){ addPoint(x0,y0); return 1; } } if(maze[x0+1][y0+1]=='\\' || (maze[x0+1][y0+1]=='|'&& mazeHistory[x0][y0+1]==0)){ if(findPath(x0+1,y0+1)==1){ addPoint(x0,y0); return 1; } } if(maze[x0][y0+1]=='/'){ if(findPath(x0,y0+1)==1){ addPoint(x0,y0); return 1; } } return 0; } return 0; }
bool TMap::gotoRoom( int r ) { mTargetID = r; return findPath( mRoomId, r ); }
bool TMap::gotoRoom( int r1, int r2 ) { //mTargetID = r2; return findPath( r1, r2 ); }
static void add_type3_font_info(SkPDFCanon* canon, SkPDFDict* font, SkTypeface* typeface, const SkBitSet& subset, SkGlyphID firstGlyphID, SkGlyphID lastGlyphID) { const SkAdvancedTypefaceMetrics* metrics = SkPDFFont::GetMetrics(typeface, canon); SkASSERT(lastGlyphID >= firstGlyphID); // Remove unused glyphs at the end of the range. // Keep the lastGlyphID >= firstGlyphID invariant true. while (lastGlyphID > firstGlyphID && !subset.has(lastGlyphID)) { --lastGlyphID; } int unitsPerEm; auto cache = SkPDFFont::MakeVectorCache(typeface, &unitsPerEm); SkASSERT(cache); SkScalar emSize = (SkScalar)unitsPerEm; font->insertName("Subtype", "Type3"); // Flip about the x-axis and scale by 1/emSize. SkMatrix fontMatrix; fontMatrix.setScale(SkScalarInvert(emSize), -SkScalarInvert(emSize)); font->insertObject("FontMatrix", SkPDFUtils::MatrixToArray(fontMatrix)); auto charProcs = sk_make_sp<SkPDFDict>(); auto encoding = sk_make_sp<SkPDFDict>("Encoding"); auto encDiffs = sk_make_sp<SkPDFArray>(); // length(firstGlyphID .. lastGlyphID) == lastGlyphID - firstGlyphID + 1 // plus 1 for glyph 0; SkASSERT(firstGlyphID > 0); SkASSERT(lastGlyphID >= firstGlyphID); int glyphCount = lastGlyphID - firstGlyphID + 2; // one other entry for the index of first glyph. encDiffs->reserve(glyphCount + 1); encDiffs->appendInt(0); // index of first glyph auto widthArray = sk_make_sp<SkPDFArray>(); widthArray->reserve(glyphCount); SkIRect bbox = SkIRect::MakeEmpty(); sk_sp<SkPDFStream> emptyStream; for (SkGlyphID gID : SingleByteGlyphIdIterator(firstGlyphID, lastGlyphID)) { bool skipGlyph = gID != 0 && !subset.has(gID); SkString characterName; SkScalar advance = 0.0f; SkIRect glyphBBox; if (skipGlyph) { characterName.set("g0"); } else { characterName.printf("g%X", gID); const SkGlyph& glyph = cache->getGlyphIDMetrics(gID); advance = SkFloatToScalar(glyph.fAdvanceX); glyphBBox = SkIRect::MakeXYWH(glyph.fLeft, glyph.fTop, glyph.fWidth, glyph.fHeight); bbox.join(glyphBBox); const SkPath* path = cache->findPath(glyph); if (path && !path->isEmpty()) { SkDynamicMemoryWStream content; setGlyphWidthAndBoundingBox(SkFloatToScalar(glyph.fAdvanceX), glyphBBox, &content); SkPDFUtils::EmitPath(*path, SkPaint::kFill_Style, &content); SkPDFUtils::PaintPath(SkPaint::kFill_Style, path->getFillType(), &content); charProcs->insertObjRef( characterName, sk_make_sp<SkPDFStream>( std::unique_ptr<SkStreamAsset>(content.detachAsStream()))); } else { if (!emptyStream) { emptyStream = sk_make_sp<SkPDFStream>( std::unique_ptr<SkStreamAsset>( new SkMemoryStream((size_t)0))); } charProcs->insertObjRef(characterName, emptyStream); } } encDiffs->appendName(characterName.c_str()); widthArray->appendScalar(advance); } encoding->insertObject("Differences", std::move(encDiffs)); font->insertInt("FirstChar", 0); font->insertInt("LastChar", lastGlyphID - firstGlyphID + 1); /* FontBBox: "A rectangle expressed in the glyph coordinate system, specifying the font bounding box. This is the smallest rectangle enclosing the shape that would result if all of the glyphs of the font were placed with their origins coincident and then filled." */ auto fontBBox = sk_make_sp<SkPDFArray>(); fontBBox->reserve(4); fontBBox->appendInt(bbox.left()); fontBBox->appendInt(bbox.bottom()); fontBBox->appendInt(bbox.right()); fontBBox->appendInt(bbox.top()); font->insertObject("FontBBox", std::move(fontBBox)); font->insertName("CIDToGIDMap", "Identity"); if (metrics && metrics->fGlyphToUnicode.count() > 0) { font->insertObjRef("ToUnicode", SkPDFMakeToUnicodeCmap(metrics->fGlyphToUnicode, &subset, false, firstGlyphID, lastGlyphID)); } auto descriptor = sk_make_sp<SkPDFDict>("FontDescriptor"); int32_t fontDescriptorFlags = kPdfSymbolic; if (metrics) { // Type3 FontDescriptor does not require all the same fields. descriptor->insertName("FontName", metrics->fPostScriptName); descriptor->insertInt("ItalicAngle", metrics->fItalicAngle); fontDescriptorFlags |= (int32_t)metrics->fStyle; // Adobe requests CapHeight, XHeight, and StemV be added // to "greatly help our workflow downstream". if (metrics->fCapHeight != 0) { descriptor->insertInt("CapHeight", metrics->fCapHeight); } if (metrics->fStemV != 0) { descriptor->insertInt("StemV", metrics->fStemV); } SkScalar xHeight = cache->getFontMetrics().fXHeight; if (xHeight != 0) { descriptor->insertScalar("XHeight", xHeight); } } descriptor->insertInt("Flags", fontDescriptorFlags); font->insertObjRef("FontDescriptor", std::move(descriptor)); font->insertObject("Widths", std::move(widthArray)); font->insertObject("Encoding", std::move(encoding)); font->insertObject("CharProcs", std::move(charProcs)); }
void ImportLibraryDialog::setupUI() { nameLabel = new QLabel(tr("Library Name : ")); nameEdit = new QLineEdit; nameLabel->setBuddy(nameEdit); connect(nameEdit,SIGNAL(textChanged(QString)),this,SLOT(nameEntered())); textLabel = new QLabel(tr("Package location : ")); path = new QLineEdit; textLabel->setBuddy(path); destLabel = new QLabel(tr("Destination folder : ")); destPath = new QLineEdit; textLabel->setBuddy(destPath); accept = new QPushButton(tr("Unpack")); accept->setDisabled(true); connect(accept,SIGNAL(clicked()),this,SLOT(add())); cancel = new QPushButton(tr("Cancel")); connect(cancel,SIGNAL(clicked()),this,SLOT(close())); //connect(cancel,SIGNAL(clicked()),this,SIGNAL(rejected())); find = new QPushButton(QIcon(":/images/coversPackage.png"),""); connect(find,SIGNAL(clicked()),this,SLOT(findPath())); findDest = new QPushButton(QIcon(":/images/open.png"),""); connect(findDest,SIGNAL(clicked()),this,SLOT(findDestination())); QGridLayout * content = new QGridLayout; content->addWidget(nameLabel,0,0); content->addWidget(nameEdit,0,1); content->addWidget(textLabel,1,0); content->addWidget(path,1,1); content->addWidget(find,1,2); content->setColumnStretch(2,0); //TODO content->addWidget(destLabel,2,0); content->addWidget(destPath,2,1); content->addWidget(findDest,2,2); //destLayout->setStretchFactor(findDest,0); //TODO QHBoxLayout *bottomLayout = new QHBoxLayout; bottomLayout->addStretch(); bottomLayout->addWidget(accept); bottomLayout->addWidget(cancel); progressBar = new QProgressBar(this); progressBar->setMinimum(0); progressBar->setMaximum(0); progressBar->setTextVisible(false); progressBar->hide(); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(content); //mainLayout->addWidget(progress = new QLabel()); mainLayout->addStretch(); mainLayout->addWidget(progressBar); mainLayout->addLayout(bottomLayout); QHBoxLayout * imgMainLayout = new QHBoxLayout; QLabel * imgLabel = new QLabel(this); QPixmap p(":/images/importLibrary.png"); imgLabel->setPixmap(p); imgMainLayout->addWidget(imgLabel); imgMainLayout->addLayout(mainLayout); setLayout(imgMainLayout); setModal(true); setWindowTitle(tr("Extract a catalog")); }
bool hasPathSum(TreeNode *root, int sum) { target_sum = sum; return findPath(root, 0); }
void Enemy::update() { Character::update(); animation(); if(!m_bDead) { float xPos = m_Sprite.getPosition().x; float yPos = m_Sprite.getPosition().y; short quarterTile = TILESIZE / 4; pathLocation = m_Path.size() - 1; short direction = -1; if(pathLocation >= 0) // If there are any pathsteps. { pathStep = m_Path[pathLocation]; float stepX = pathStep -> x + quarterTile; // Check for middle of tile. float stepY = pathStep -> y + quarterTile; if((xPos + TILESIZE) < stepX) // right side { direction = 2; // east } else if(xPos > stepX) // left side { direction = 6; // West } else { xStepGoalReached = true; } if((yPos + TILESIZE) < stepY) // bottom { if(direction == EAST) { direction = SOUTH_EAST; // south-East } else if(direction == WEST) { direction = SOUTH_WEST; // south-west } else { direction = SOUTH; // south. } } else if(yPos > stepY) // top { if(direction == EAST) { direction = NORTH_EAST; // north east } else if(direction == WEST) { direction = NORTH_WEST; // north-west. } else { direction = NORTH; // north } } else { yStepGoalReached = true; } if(direction != -1) { move(direction); } if(xStepGoalReached && yStepGoalReached) { m_Path.erase(m_Path.end() - 1); xStepGoalReached = false; yStepGoalReached = false; } } else { short attackGoalX = m_pPlayerPos -> x + quarterTile; short attackGoalY = m_pPlayerPos -> x + quarterTile; // if coming from the left, and within attackRange. if(xPos < attackGoalX && abs((xPos + TILESIZE) - (attackGoalX)) < m_fAttackRange) { m_bTryAttack = true; } else if(xPos >= attackGoalX && abs((xPos) - (attackGoalX)) < m_fAttackRange) // Coming from the right { m_bTryAttack = true; } else if(yPos < attackGoalY && abs((yPos + TILESIZE) - (attackGoalY)) < m_fAttackRange) // From above. { m_bTryAttack = true; } else if(yPos >= attackGoalY && abs((yPos) - (attackGoalY)) < m_fAttackRange) // From below. { m_bTryAttack = true; } else // Not within range. { m_bTryAttack = false; findPath(xPos, yPos, m_pPlayerPos -> x, m_pPlayerPos -> y); } if(m_bTryAttack) { m_Sprite.setTexture((*m_TextureTypes[ATTACK])); m_bDoingAction = true; } } } }
buildTree() { internalID = seqlength; clock_t Start_t= clock(); //record time that task 1 begins root = makenode(-1,-1,internalID,0); root->parent=root; root->sl=root; internalID++; //////////printf("internal ID %d\n", internalID); NODE * p=root; //printf("%d\n", p); int s =0; for (s =0; s<l;s++) { //printf("++++++++++++++++++++++++++\n"); //printf("iter %d, %d, %d, %d, %d\n", s, p->id, p->start, p->end, p->depth); //printf("++++++++++++++++++++++++++\n"); // printTree(root); if(p->parent->sl) { p=p->parent->sl; int i=s+p->depth; p= findPath(i,p,s); continue; } else { NODE * u= p->parent; NODE *v= u->parent->sl; int b= 0; int i=s; if(u->parent==root) { ////printf("II B \n"); b= u->end-u->start; } else { ////printf("II A \n"); b = u->end - u->start +1; i+=v->depth; } p= nodhop(&i, b,v); ////////printf("return of nodehop %d, %d\n", i, v->id); u->sl=p; p=findPath(i, p, s); } } clock_t End_t = clock(); printf("Build Tree Time %ld clock with rate %d (cps)\n ", End_t-Start_t, CLOCKS_PER_SEC); printf("#internal %d, #leaves %d, #total %d, size %d\n", internalID -seqlength, seqlength,internalID, internalID*sizeof(NODE)); }
int uniquePaths(int m, int n) { vector<vector<int>> cache(m+1,vector<int>(n+1,-1)); return findPath(cache,m,n); }
int main(int argc, char **argv) { while(1) //shell runs till user enters exit { char * cwd = malloc(256); //find current working directory for prompt assert(cwd != NULL); getCurrentDir(cwd); printf("\nMyShell:%s$ ", cwd); //print shell prompt free(cwd); char *consoleinput = malloc(256); assert(consoleinput != NULL); //TO DO: Change buffer size to variable readCommand(consoleinput); //accept input removeNewLineChar(consoleinput); //remove '\n' character from input removeWhiteSpaces(consoleinput); //remove all spaces before and after command if(strncmp(consoleinput, SUPPORTED_COMMANDS[1], 4) == 0) //exit { free(consoleinput); printf("\nMyShell Terminated\n"); return 0; } else if(strncmp(consoleinput, SUPPORTED_COMMANDS[0], 2) == 0) //cd { int result = runChangeDir(consoleinput); if(result!=0) { perror("cd error:"); } } else if(strncmp(consoleinput, SUPPORTED_COMMANDS[2], 4) == 0) //path { int result = runPath(consoleinput); if(result!=0) { errno = result; perror("path error:"); } } else { //handle pipes char **commands = parseArgv(consoleinput, SPECIAL_CHARS[4]); //input destoyed int numcommands = 0; while( commands[numcommands]!=NULL ) { numcommands++; } //printf("\nNumber of commands:[%d]", numcommands); const int numpipes = 2*(numcommands-1); //printf("\nNumber of pipe file descriptors:[%d]", numpipes); /*read and write ends of pipes stay apart by 3 -increment open pipe indexes by 2 after every command -close all pipes */ int pipefds[numpipes]; int i=0; for(i=0; i<numpipes;i=i+2) { pipe(pipefds+i); } //printf("\npipe() call successful"); // for(i=0;i<numpipes;i++) // { // printf("[%d]", pipefds[i]); // } int pipe_w = 1; int pipe_r = pipe_w - 3; int curcommand = 0; while(curcommand < numcommands) { //printf("\nCommand number:[%d]", curcommand); //printf("\ninside pipe loop for command [%s]", commands[curcommand]); //Parse Command and Arguments into formatneeded by execv char **argv = parseArgv(commands[curcommand], SPECIAL_CHARS[0]); //printf("\nCurrent Command:[%s]", argv[0]); if(findPath(argv) == 0) { //executeCommand(argv); int child_pid = fork(); //int child_status; if(child_pid < 0) { //errno = 3; perror("fork error:"); } else if(child_pid == 0) //fork success { if(pipe_w < numpipes) { //open write end //printf("\nWrite pipe:[%d] to stdout", pipefds[pipe_w]); if(dup2(pipefds[pipe_w], 1) < 0) { perror("pipe write-end error: "); } } if((pipe_r >= 0)&&(pipe_r < numpipes)) { //open read end //printf("\nRead pipe:[%d] to stdin", pipefds[pipe_r]); if(dup2(pipefds[pipe_r], 0) < 0) { perror("pipe read-end error: "); } } for(i=0;i<numpipes;i++) //close off all pipes { //printf("\nclosing all pipes"); close(pipefds[i]); } if(execv(argv[0], argv) == -1) { perror("Bad command or filename:"); exit(0); //TODO: child hangs here } //fflush(stdin); } } else { printf("\nBad command or filename"); //TODO: ForkBomb occuring here //exit(0); } free(argv); //printf("\nIncrementing pipe ends, moving to next command."); curcommand++; pipe_w = pipe_w + 2; pipe_r = pipe_r + 2; } //int i=0; for(i=0;i<numpipes;i++) //close off all pipes { //printf("\nclosing all pipes"); close(pipefds[i]); } int status; for(i=0;i<numcommands;i++) { wait(&status); } free(commands); } free(consoleinput); } freeList(pathlist); }