Esempio n. 1
0
// the overall motion of ghost
     void motion(int &xg,int &yg,int x,int y,char &cg,int blackSquare[][28],int &ig,int &v){
		int p=xg-44;int q=yg-50;
//v is used to make ghost follow pac only for particular time interval

	if(((ab((x-xg))+ab((y-yg)))<200)&&(v<=3)){v++;

	if(cg=='w'){if((p%20==0)&&(q%20==0)&&((blackSquare[(q/20)][(p/20)-1]==1)||(blackSquare[(q/20)][(p/20)+1]==1)))
	{shortestPath(xg,yg,x,y,cg,blackSquare);return;}
	            else{yg=yg-5;return;}};
	if(cg=='a'){if((p%20==0)&&(q%20==0)&&((blackSquare[(q/20)-1][(p/20)]==1)||(blackSquare[(q/20)+1][(p/20)]==1)))
	{shortestPath(xg,yg,x,y,cg,blackSquare);return;}
	            else{{xg=xg-5;return;}};}
	if(cg=='s'){if((p%20==0)&&(q%20==0)&&((blackSquare[(q/20)][(p/20)-1]==1)||(blackSquare[(q/20)][(p/20)+1]==1)))
	{shortestPath(xg,yg,x,y,cg,blackSquare);return;}
	            else{yg=yg+5;return;}};
	if(cg=='d'){if((p%20==0)&&(q%20==0)&&((blackSquare[(q/20)-1][(p/20)]==1)||(blackSquare[(q/20)+1][(p/20)]==1)))
	{shortestPath(xg,yg,x,y,cg,blackSquare);return;}
	            else{xg=xg+5;return;}}};
    v=0;
	if(ig%5==1){
	if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}};
	if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}};
	if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}};
	if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}};
	};

	if(ig%5==2){
	if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}};
	if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}};
	if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}};
	if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}};
	};
	
	if(ig%5==3){
	if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}};
	if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}};
	if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}};
	if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}};};
	
	if(ig%5==4){
	if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}};
	if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}};
	if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}};
	if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}};};
	
	if(ig%5==0){
	if(cg!='s'){if(possible(xg,yg,cg,'w',blackSquare)){cg='w';yg=yg-5;ig++;return;}};
	if(cg!='w'){if(possible(xg,yg,cg,'s',blackSquare)){cg='s';yg=yg+5;ig++;return;}};
	if(cg!='d'){if(possible(xg,yg,cg,'a',blackSquare)){cg='a';xg=xg-5;ig++;return;}};
	if(cg!='a'){if(possible(xg,yg,cg,'d',blackSquare)){cg='d',xg=xg+5;ig++;return;}};};
	
	}
void FloydWarshall::shortestPath(int **pij, int i, int j)
{
    if((i != -1) && (j != -1))
    {
        int k = pij[i][j];

        if(k > 0)
        {
            shortestPath(pij, i, k);
            cout << " " << k;
            shortestPath(pij, k, j);
        }
    }
}
int main()
{
    const std::vector<std::vector<int>> matrix = 
        {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
         { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
         { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
         { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
         { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
         { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
         { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
         { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
         { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};
    
    Point source = {0, 0};
    Point destination = {3, 4};
    int distance = shortestPath(matrix, source, destination);
    if (distance != 
        std::numeric_limits<int>::max())
    {
        std::cout << "The distance between ("
            << source.x << ", " << source.y
            << ") and destination (" << destination.x
            << ", " << destination.y << ") is "
            << distance << std::endl;
    }
    else
    {
        std::cout << "The path does not exist between ("
            << source.x << ", " << source.y
            << ") and destination (" << destination.x
            << ", " << destination.y << ") is "
            << distance << std::endl;
    }
    return 0;
}
Esempio n. 4
0
void findPath(struct maze* theMaze)
{
	int iStartNode = theMaze->starty * theMaze->numcols + theMaze->startx;
	int iExitNode = theMaze->exity * theMaze->numcols + theMaze->exitx;
	
	return (shortestPath(theMaze, iStartNode, iExitNode));
}
Esempio n. 5
0
int main(int argc, char **argv)
{
	int id1, id2, errs=0;

	if (argc < 3) {
		fprintf(stderr, "Usage: %s Place1 Place2\n", argv[0]);
		exit(1);
	}

	// convert args to place IDs
	id1 = (strlen(argv[1]) == 2) ? abbrevToID(argv[1]) : nameToID(argv[1]);
	id2 = (strlen(argv[1]) == 2) ? abbrevToID(argv[2]) : nameToID(argv[2]);

	// check place validity
	if (id1 == NOWHERE) {
		errs++;
		fprintf(stderr, "Invalid place name: %s\n", argv[1]);
	}
	if (id2 == NOWHERE) {
		errs++;
		fprintf(stderr, "Invalid place name: %s\n", argv[2]);
	}
	if (errs > 0) exit(1);

	Map europe;
	europe = newMap();

	// find shortest path
	int i, n;
    LocationID path[NUM_MAP_LOCATIONS];
	TransportID trans[NUM_MAP_LOCATIONS];

	printf("Starting from %s ...\n", idToName(id1));
	n = shortestPath(europe, id1, id2, path, trans);
	if (n == 0)
		printf("you cannot reach %s\n", idToName(id2));
	else {
		for (i = 1; i < n; i++) {
			if (i > 1 && n > 2) printf("then ");
			printf("go to %s by ", idToName(path[i]));
			switch (trans[i]) {
			case ROAD: printf("road\n"); break;
			case RAIL: printf("rail\n"); break;
			case BOAT: printf("boat\n"); break;
			default:   printf("????\n"); break;
			}
		}
		printf("You have reached your destination\n");
	}

	//DEBUG
    printf("start is: %d; end is: %d\n", id1, id2);
    printf("path[0] is: %d; path[1] is: %d\n", path[0], path[1]);

	return 0;
}
//Simply Display all pair shortest path
void Spath::allPairShortestPath(){
	cout<<"All pair Shortest Path\n";
	for(int source=1;source<=vertices.size();source++){
		bfs(source);	//source vertex
		for(int dest=1;dest<=vertices.size();dest++){
			printf("(%d,%d) : ",source,dest);
			shortestPath(source,dest);
			cout<<endl;
		}
	}	
}
tf::Pose relativePose (const ConstraintGraph& g, const unsigned n1,
                       const unsigned n2)
{
  const Graph& graph = g.graph();
  ShortestPath path = shortestPath(g, n1, n2);
  tf::Pose p;
  p.setIdentity();
  BOOST_FOREACH (const unsigned e, path.second)
    p *= util::toPose(graph[g.idEdge(e)].constraint.constraint.pose);
  return p;
}
Esempio n. 8
0
int solve() {
	Graph g;
	int path[SIZE], length, n, i;

	int source, target;

	source = 1;
	target = 3;

	if((g = createGraph()) == NULL) {
		return 1;
	}

	addVertex(g, 1, "Blah");
	addVertex(g, 2, "Blah blah");
	addVertex(g, 3, "Blah blah");
	addVertex(g, 4, "Blah blah");
	addVertex(g, 5, "Blah blah");
	addVertex(g, 6, "Blah blah");
	// addVertex(g, 7, "Blah blah");

	addEdge(g, 1, 2, 1);
	addEdge(g, 1, 4, 1);
	addEdge(g, 2, 3, 1);
	addEdge(g, 4, 6, 1);
	addEdge(g, 5, 6, 1);
	addEdge(g, 6, 3, 1);
	// addEdge(g, 3, 4, 1);

	if(checkCycle(g)) {
		printf("The graph has a cycle\n");
	} else {
		printf("The graph has no cycle\n");
	}

	int weight;
	weight = shortestPath(g, source, target, path, &length);

	if(weight == INFINITIVE_VALUE)
		printf("No path between %d and %d\n", source, target);
	else {
		printf("Path between %d and %d\n", source, target);
		for(i = 0; i < length; i++)
			printf("%4d\n", path[i]);
		printf("Total weight: %d\n", weight);
	}

	dropGraph(g);

	return 0;
}
void FloydWarshall::printShortestPath(Floyd floyd, int i, int j)
{
    if(floyd.dij[i][j] < INFINITE)
    {
        cout << "O caminho entre os nós " << i << " e " << j << " é: ";
        cout << i;
        shortestPath(floyd.pij, i, j);
        cout << " " << j << endl;
    }
    else
    {
        cout << "[ Erro ]: Não há caminho entre o nó " << i << " e o nó " << j << endl;
    }
}
//Shortest Path Fixed Vertex (Source->Destination) from breadth first tree
void Spath::shortestPath(int source,int destination){
	shortestPathLength++;
    if(source==destination)
	cout<<source;
    else if(vertices[destination-1].parent==NULL){
	cout<<"No Path from "<<source<<" to "<<destination<<" exists\n";
    }
    else{
	int new_dest=vertices[destination-1].parent->key+1;
	shortestPath(source,new_dest);
	cout<<"->"<<destination;
    }

}
Esempio n. 11
0
/* makePath:
 * Given two points p and q in two polygons pp and qp of a vconfig_t conf, 
 * and the visibility vectors of p and q relative to conf, 
 * compute the shortest path from p to q.
 * If dad is the returned array and V is the number of polygon vertices in
 * conf, then the path is V(==q), dad[V], dad[dad[V]], ..., V+1(==p).
 * NB: This is the only path that is guaranteed to be valid.
 * We have dad[V+1] = -1.
 * 
 */
int *makePath(Ppoint_t p, int pp, COORD * pvis,
	      Ppoint_t q, int qp, COORD * qvis, vconfig_t * conf)
{
    int V = conf->N;

    if (directVis(p, pp, q, qp, conf)) {
	int *dad = (int *) malloc(sizeof(int) * (V + 2));
	dad[V] = V + 1;
	dad[V + 1] = -1;
	return dad;
    } else {
	array2 wadj = conf->vis;
	wadj[V] = qvis;
	wadj[V + 1] = pvis;
	return (shortestPath(V + 1, V, V + 2, wadj));
    }
}
Esempio n. 12
0
void Polygon_salesperson (Polygon me, long numberOfIterations) {
	try {
		long numberOfShortest = 1, totalDistance, shortestDistance = 0;

		int numberOfCities = my numberOfPoints;
		if (numberOfCities < 1)
			Melder_throw (U"No points.");
		autoNUMmatrix <int> distance (1, numberOfCities, 1, numberOfCities);
		computeDistanceTable (me, distance.peek());
		autoNUMvector <int> path (0L, numberOfCities);
		for (int i = 1; i <= numberOfCities; i ++)
			path [i] = i;
		path [0] = numberOfCities;   // close path
		autoNUMvector <int> shortestPath (NUMvector_copy (path.peek(), 0, numberOfCities), 0);
		for (long iteration = 1; iteration <= numberOfIterations; iteration ++) {
			if (iteration > 1) shuffle (path.peek(), numberOfCities);
			totalDistance = computeTotalDistance (distance.peek(), path.peek(), numberOfCities);
			if (iteration == 1) shortestDistance = totalDistance;
			do {
				do {
				} while (tryExchange (distance.peek(), path.peek(), numberOfCities, & totalDistance));
			} while (tryAdoption (distance.peek(), path.peek(), numberOfCities, & totalDistance));
			if (totalDistance < shortestDistance) {   // new shortest path
				numberOfShortest = 1;
				for (int i = 0; i <= numberOfCities; i ++) shortestPath [i] = path [i];
				shortestDistance = totalDistance;
			}
			else if (totalDistance == shortestDistance)   // shortest path confirmed
				numberOfShortest ++;
		}
		if (numberOfIterations > 1)
			Melder_casual (U"Polygon_salesperson:"
				U" found ", numberOfShortest,
				U" times the same shortest path.");

		/* Change me: I will follow the shortest path found. */

		autoPolygon help = Data_copy (me);
		for (long i = 1; i <= numberOfCities; i ++) {
			my x [i] = help -> x [shortestPath [i]];
			my y [i] = help -> y [shortestPath [i]];
		}
	} catch (MelderError) {
		Melder_throw (me, U": shortest path not found.");
	}
}
//Longest Path in a tree
void Spath::longestPath(){
	bfs(1);	//First bfs
	//Farthest node
	int max=0,max_distance=vertices[0].distance;
	for(int i=1;i<no_of_vertices;i++){
		if(vertices[i].distance>max_distance){
			max=i;
			max_distance=vertices[i].distance;
		}
	}
	bfs(max+1);	//Second BFS
	int source=0;
	max_distance=vertices[0].distance;
	for(int i=1;i<no_of_vertices;i++){
		if(vertices[i].distance>max_distance){
			source=i;
			max_distance=vertices[i].distance;
		}
	}
	cout<<source+1<<"->"<<max+1<<endl;
	shortestPath(max+1,source+1);	//Longest Path
}
Esempio n. 14
0
int main(int argc, char** argv)
{
  Node** g  ;
  int i;
  int j;
  int size;
  FILE* f = fopen(argv[1],"r");
  g = loadfile(f, &size);
  
  shortestPath(g,size);
  int min = size*size;
  
  int dist = size*size;
  for(i = 0; i<size-1;i++)
    {
      if(g[i][0].dist<dist)
	{
	  dist = g[i][0].dist;
	}
    }

  fclose(f);
  for(i = 0;i < size-1;i++)
    {
      for(j = 0;j < size;j++)
	{
	  printf("%d",g[i][j].weight);
	}
      printf("\n");
      free(g[i]);
    }
  
  free(g);
  printf("%d\n",dist);
  return EXIT_SUCCESS;

}
Esempio n. 15
0
struct path_node *mouseEscape(int GamePos[numAgents][3],float A[GsizeSqr][GsizeSqr])
{
 /*
   Implement this function to create the smartest mouse possible

   a smart mouse can update function designed to elude even the smartest cat.

    Note that: The mouse can see the kitties (since the mouse would usually be
               user controlled, we assume the mouse sees where the kitties are).
               The mouse can also measure distance to the kitties.
               Of course, the mouse knows where the cheese and gate are.

    Design a maze traveling approach that gives the mouse a chance to escape even
    kitties using kittyAIcheat() or superKitty(). This will involve carefully
    managing the graph to account for cat position and proximity while optimizing
    the path to the cheese and the output.
 */

  struct path_node *path=NULL;
  struct path_node *head=NULL;  // it is used in travesal in linked list- path-node
  int flagCatInPath = 0;    // it indicates if there is a cat in the mouse's shortest path
                           // 0 means none, 1 means there is a hungry cat waiting there!
  int nearestCatInpath = -1;  // it stores which cat is in mouse's way
  int dx, dy;     // store distance in x-axis, and y-axis


   // Check if cheese was being eaten
  if (!GamePos[2][2])   // cheese has not been eaten
     path=shortestPath(A,GamePos[1][0],GamePos[1][1],GamePos[2][0],GamePos[2][1]); 
     //path=shortestPath(A,GamePos[1][0],GamePos[1][1], 19, 19);        // debug....................
  else
	 // done with chees, move to exit gate!
     path=shortestPath(A,GamePos[1][0],GamePos[1][1],GamePos[0][0],GamePos[0][1]);
    
     //GamePos[1][0] = 19;          //debug, let the mouse stuck somewhere......................
	 //GamePos[1][1] = 0;
	 //path=NULL;

  if(!path) return NULL;
    
  // the while is to find if there is a cat in mouse' path
  head = path->next;
  while(head)
  {
	  for (int i=3;i<numAgents;i++)
	  {
		  if ((head->x == GamePos[i][0]) &&
			  (head->y == GamePos[i][1]))
		  {
				flagCatInPath = 1;     //1 means there is a hungry cat waiting there!
		        nearestCatInpath = i;  // keep a record of which cat is waiting for the mouse!
				break;
		  }
	  }
      if (flagCatInPath) break;
	  head = head->next;
  }

  // check there is a cat near the mouse
  for (int i=3;i<numAgents;i++)
  {
	  dx = GamePos[i][0] - GamePos[1][0]; // get x-axis distance 
      dy = GamePos[i][1] - GamePos[1][1];  // get y-axis distance
	  if ((abs(dx)+abs(dy))<=2)
	  {
			flagCatInPath = 1;     //1 means there is a hungry cat waiting there!
	        nearestCatInpath = i;  // keep a record of which cat is waiting for the mouse!
	  }
  }

  if (!flagCatInPath) return path;    // it's safe to go, no cats in my way!


  //set the destination one grid different from cat's position
  // check four conor grids around the cat, if it's valid postion, move there tempararily
  if(((GamePos[nearestCatInpath][0]-2)>0)&&((GamePos[nearestCatInpath][1]-2)>0))
  {
	path=shortestPath(A,GamePos[1][0],GamePos[1][1],
		GamePos[nearestCatInpath][0]-2,GamePos[nearestCatInpath][1]-2);
	flagCatInPath=0; 
	return path;   // get the shortest destinated at upper left cornor grid of the cat.
	              // avoiding be seen by cat
  }
  if(((GamePos[nearestCatInpath][0]+2)>0)&&((GamePos[nearestCatInpath][1]-2)>0))
  {
	path=shortestPath(A,GamePos[1][0],GamePos[1][1],
		GamePos[nearestCatInpath][0]+2,GamePos[nearestCatInpath][1]-2);
	flagCatInPath=0; 
	return path;   // get the shortest destinated at upper right cornor grid of the cat.
	              // avoiding be seen by cat
  }
  if(((GamePos[nearestCatInpath][0]-2)>0)&&((GamePos[nearestCatInpath][1]+2)>0)) 
  {
	path=shortestPath(A,GamePos[1][0],GamePos[1][1],
		GamePos[nearestCatInpath][0]-2,GamePos[nearestCatInpath][1]+2);
	flagCatInPath=0; 
	return path;  // get the shortest destinated at lower left cornor grid of the cat.
	              // avoiding be seen by cat
  }
  if(((GamePos[nearestCatInpath][0]+2)>0)&&((GamePos[nearestCatInpath][1]+2)>0))
  {
	path=shortestPath(A,GamePos[1][0],GamePos[1][1],
		GamePos[nearestCatInpath][0]+2,GamePos[nearestCatInpath][1]-2);
	flagCatInPath=0; 
	return path;   // get the shortest destinated at lower right cornor grid of the cat.
	              // avoiding be seen by cat
  }

  //return path; 
}
Esempio n. 16
0
struct path_node *kittySoundWalk(int GamePos[numAgents][3], float A[GsizeSqr][GsizeSqr], int Target[numAgents][2], int kitty)
{
 /*
   Kitty sound walk: Expected behaviour:

   In space no one can hear you scream, unfortunately, we're not in space, so the
   mouse's little steps can be heard by hungry kitties.

   This function works by checking whether the mouse is closer than 'hearingRadius'
   away from a kitty. If so, the cat can hear the mouse and will use the shortest
   path to reach the mouse's location.

   ** As long as the mouse remains within hearing radius, the shortest path is
   ** updated at each turn (unlike kittySmartSmell() which computed a destination
   ** once and then had to wait for the cat to arrive there)

   If the mouse steps outside the hearing radius, the cat still has to complete
   the trip to the last known mouse location.

   As long as the mouse has not stepped within hearing radius, or if it stepped
   out and the cat reached the last known mouse location, the cat reverts to
   smell based mouse finding (you should use kittySmellWalk() for that - why
   can't you use kittySmartSmell()? )

   All distances are Manhattan distances.

   Depending on the value of hearingRadius (see GameAI.h), this could make the
   kitties pretty tough to beat, so don't make hearingRadius too large or the
   poor mouse doesn't stand a chance!

   Grid locations over which the mouse can be heard by one of the kitties
   will be shown in dark red on each frame.
 */

 struct path_node *path=NULL;
 struct path_node *shortestpath=NULL;
 int dx, dy;     // store distance in x-axis, and y-axis

 dx = GamePos[kitty][0] - GamePos[1][0]; // get x-axis distance 
 dy = GamePos[kitty][1] - GamePos[1][1];  // get y-axis distance

 //printf("dx=%d, dy=%d\n", dx, dy); // debug......................................................

 if ((abs(dx)+abs(dy)) <= hearingRadius)
 {
    Target[kitty][0] = GamePos[1][0];  // record the position of the mouse 
    Target[kitty][1] = GamePos[1][1];
    shortestpath = shortestPath(A,GamePos[kitty][0],GamePos[kitty][1],Target[kitty][0],Target[kitty][1]);
    if(shortestpath) path = newPathNode(shortestpath->next->x, shortestpath->next->y); // obtain next move for the kitty
    if(shortestpath) deletePath(shortestpath);   // to prevent memory leak, remove the path every time
    
	flagTarget[kitty] = 1;  // flag indicates the Target has been used
	return path;
 }
 //printf("k=%d, kx=%d, ky=%d, tkx=%d, kty=%d\n",kitty, GamePos[kitty][0],
	// GamePos[kitty][1], Target[kitty][0], Target[kitty][1]);                    // debug...............
 
 // the mouse is away form sound range, and the kitty still move toward to target position!
 if (!(GamePos[kitty][0]==Target[kitty][0]&&GamePos[kitty][1]==Target[kitty][1])&&
	 Target[kitty][0] != -1)
 {
    shortestpath = shortestPath(A,GamePos[kitty][0],GamePos[kitty][1],Target[kitty][0],Target[kitty][1]);
    if(shortestpath) path = newPathNode(shortestpath->next->x, shortestpath->next->y);
    if(shortestpath) deletePath(shortestpath);

	flagTarget[kitty] = 1;  // flag indicates the Target has been used
    return path;
 }
 Target[kitty][0] = -1;  // reset the last know mouse location
 Target[kitty][1] = -1;

 path = kittySmellWalk(GamePos,A,kitty);  // smell the mouse, find next grid to move
 
 flagTarget[kitty] = 1;  // flag indicates the Target has been used
 return path;
}
Esempio n. 17
0
struct path_node *kittySmartSmell(int GamePos[numAgents][3], float A[GsizeSqr][GsizeSqr], int Target[numAgents][2], int kitty)
{
 /*
   Kitty walk using smart smell. Expected behaviour:

   As long as the kitty is not stuck, it uses smell just like the kittySmellWalk()
   function (in fact, you're allowed to call that function from here if you
   like).

   A kitty that has reached a dead end is allowed to use the shortest path
   algorithm to find the best route to go to the other side of whichever
   wall is blocking it.

   Once the cat switches to shortest-path, it MUST reach the intended target
   destination.

   After the kitty has arrived at its intended destination, it reverts to
   using smell to track the mouse.
 */
    
 struct path_node *path=NULL;
 struct path_node *shortestpath=NULL;
 int dx, dy;     // store distance in x-axis, and y-axis

 // there are two mode here, one is shortestpath mode where target position is set
 // another is smellWalk mode where target position is not set ( the kitty is not
 // stuck
 if (GamePos[kitty][0]==Target[kitty][0] && GamePos[kitty][1]==Target[kitty][1] ||
	 Target[kitty][0]==-1)
 {   
	 // the mouse changed its position, or the kitty reached intended target postion
	 //it's in smellWalk mode

	 Target[kitty][0] = -1;  // it's very important to reset target in smelWalk mode
	 Target[kitty][1] = -1;  

	 path = kittySmellWalk(GamePos,A,kitty);  // smell the mouse, find next grid to move
	 
	 if(path) // if the kitty is not stuck
	 {
		 if (kitty==7)   // update the mouse's postion only after all kitties complete smartSmellWalk!
		 {
			Target[1][0] = GamePos[1][0]; // keep record of the mouse's location, since 
			Target[1][1] = GamePos[1][1]; // the mouse always moves first
		 }
		 return path; // as long as the kitty is not stuck, keep smelling and moving!
	 }
	 // if we consider the game grid layou as a x-y quardrants, and the kitty is vertex
	 // the mouse may fall into 4 quardrants, x-axis or y axis 
	 dx = GamePos[kitty][0] - GamePos[1][0]; // get x-axis distance 
	 dy = GamePos[kitty][1] - GamePos[1][1];  // get y-axis distance

	 //set up the target. there are four scenarios for the kitty getting stuck.
	 if(dy > 0)  // scenario 1: 2nd and 1 quardrant and +y axis
	 {
		 // if the mouse is in 2nd quardrant or +y axis , the kitty can only move to
		 //left or up in order to be closer to the mouse
		 Target[kitty][0] = GamePos[kitty][0]; 
		 Target[kitty][1] = GamePos[kitty][1]-1;  // up one grid behind the wall 
	 }
	 if(dy < 0)  // scenario 2: 3rd, 4th quardrant and -y axis
	 {
		 Target[kitty][0] = GamePos[kitty][0]; 
		 Target[kitty][1] = GamePos[kitty][1]+1;  // down one grid behind the wall 
	 }

	 if(dx < 0 && dy == 0)  // scenario 3: +x axis
	 {
 		 Target[kitty][0] = GamePos[kitty][0]+1;   // move right one grid behind the wall 
		 Target[kitty][1] = GamePos[kitty][1];
	 }
	 if(dx > 0 && dy == 0)  // scenario 4: -x axis
	 {
		 Target[kitty][0] = GamePos[kitty][0]-1;   // move left one grid behind the wall 
		 Target[kitty][1] = GamePos[kitty][1];
	 }
 }

 // shortest path mode

 // as soon as we get the target postion, we compute the shortest path for the kitty
 shortestpath = shortestPath(A,GamePos[kitty][0],GamePos[kitty][1],Target[kitty][0],Target[kitty][1]);
 if(shortestpath) path = newPathNode(shortestpath->next->x, shortestpath->next->y); // obtain next move for the kitty
 if(shortestpath) deletePath(shortestpath);   // to prevent memory leak, remove the path every time

 return path;

}// end of smartSmellWalk(), don't delete
Esempio n. 18
0
struct path_node *kittyEyeWalk(int GamePos[numAgents][3], float A[GsizeSqr][GsizeSqr], int kitty)
{
 /*
   Kitty walk based on vision. The kitty behaviour is as follows:

   If the mouse is visible to the cat (aligned horizontally or
   vertically, *with no walls in between*), the kitty will move
   toward the mouse.

   Otherwise, the kitty will choose randomly from available
   neighbours.
   
   This function returns a *single* node path with
   the next position for the corresponding kitty.
 */

 struct path_node *path=NULL;
 struct path_node *head=NULL;

 int distance=0;  // distance between the kitty and the mouse

 // store up, down, left and right neighbor-nodes of kitty , [:][0]-x, [:][1]-y
 // initialize to -1 meaning no neibours
 int adjacency_list[4][2] = {-1, -1, -1, -1, -1, -1, -1, -1}; 

 int adj_index = 0;  // keep tracking the index of adjacency_list

 path=shortestPath(A,GamePos[kitty][0],GamePos[kitty][1],GamePos[1][0],GamePos[1][1]);

 if (path)
 {
   head = path;
   while(head->next)
   {
     distance++;
     head = head->next;
   }
   
   // the followings are based on a mathematical theorithm: the shortest
   // distance between two vertices is a straight line connecting them.
   // if two verices' horizontal distance is equal to shortest path, then it
   // means there is no walls between them horizontally. The same applys to 
   //vetical distance.

   if ((abs(GamePos[1][0] - GamePos[kitty][0]) == distance) ||
       (abs(GamePos[1][1] - GamePos[kitty][1]) == distance))
   {
	   head = newPathNode(path->next->x, path->next->y);  
       deletePath(path);      //delete node. prevent memory leak!

       flagRamdomPos = 0;  // it indicates that a ramdom position is being selected.
	   return head; 
   }
   // kitty randomly moves to one of its neigbours

   // loop up four neibours, check if their existance
   // up neighbor (x, y)
 
   if (GamePos[kitty][1]>0 &&
        (A[GamePos[kitty][1]*Gsize+GamePos[kitty][0]][(GamePos[kitty][1]-1)*Gsize+GamePos[kitty][0]])==1.0)
   {
       adjacency_list[adj_index][0] = GamePos[kitty][0];  // up -x
       adjacency_list[adj_index][1] = GamePos[kitty][1]-1;  // up -y
       adj_index++;
   } 
   // down neighbor (x, y)
   if (GamePos[kitty][1]<19 &&
        (A[GamePos[kitty][1]*Gsize+GamePos[kitty][0]][(GamePos[kitty][1]+1)*Gsize+GamePos[kitty][0]])==1.0)
   {
       adjacency_list[adj_index][0] = GamePos[kitty][0];  // down -x
       adjacency_list[adj_index][1] = GamePos[kitty][1]+1;  // down -y
       adj_index++;
   } 
   // left neighbor (x, y)
   if (GamePos[kitty][0]>0 &&
       (A[GamePos[kitty][1]*Gsize+GamePos[kitty][0]][GamePos[kitty][1]*Gsize+(GamePos[kitty][0]-1)])==1.0)
   {
       adjacency_list[adj_index][0] = GamePos[kitty][0]-1;  // left -x
       adjacency_list[adj_index][1] = GamePos[kitty][1];  // left -y
       adj_index++;
   } 
   // right neighbor (x, y)
   if (GamePos[kitty][0]<19 &&
        (A[GamePos[kitty][1]*Gsize+GamePos[kitty][0]][GamePos[kitty][1]*Gsize+GamePos[kitty][0]+1])==1.0)
   {   
       adjacency_list[adj_index][0] = GamePos[kitty][0]+1;  // right -x
       adjacency_list[adj_index][1] = GamePos[kitty][1];  // right -y
       adj_index++;
   }
     
   if (adj_index > 0) // found at least one neigbour
   {
       // generator a random number between [0, adj_index-1] inclusive
       adj_index = (int)(drand48()*(adj_index-1+0.99));
       path = newPathNode(adjacency_list[adj_index][0], adjacency_list[adj_index][1]); 

       flagRamdomPos = 1;  // it indicates that a ramdom position is being selected.
	   return path;
   }

 } // end of fist if, (no path found).

 return NULL;    // no shortestPath found or no valid neibours
} // end of kittyEyeWalk()
Esempio n. 19
0
int main(int argc, char *argv[]) {
  // Usage message
  if (argc < 3) {
    usage_msg();
    return EXIT_FAILURE;
  }

  int mode; // mode of output
  char *a, *b;

  if (strcmp("components",argv[2]) == 0) {
    mode = MODE_COMPONENTS;
  } else if (strcmp("degrees",argv[2]) == 0) {
    mode = MODE_DEGREES;
  } else if (strcmp("path",argv[2]) == 0) {
    mode = MODE_PATH;
  } else if (strcmp("stats",argv[2]) == 0) {
     mode = MODE_STATS;
  } else if (strcmp("diameter",argv[2]) == 0) {
     mode = MODE_DIAMETER;
  } else {
    usage_msg();
  }

  if (mode & MODE_PATH) {
    if (argc < 5 || strlen(argv[3]) < 3 || strlen(argv[4]) < 3) {
      fprintf(stderr, "Please specify two 3-letter words\nExample: 3words path bus car\n");
      return EXIT_FAILURE;
    }
    a = argv[3];
    b = argv[4];
    if (a[0]<'a'||a[0]>'z'||a[1]<'a'||a[1]>'z'||a[2]<'a'||a[2]>'z'||b[0]<'a'||b[0]>'z'||b[1]<'a'||b[1]>'z'||b[2]<'a'||b[2]>'z') {
      fprintf(stderr, "Please only use lower case 3-letter words\nExample: 3words path bus car\n");
      return EXIT_FAILURE;
    }
  }

  // Open file
  FILE *f_input = fopen(argv[1], "r");
  if (!f_input) {
    fprintf(stderr, "File could not be opened: %s\n", argv[1]);
    return EXIT_FAILURE;
  }

  NODE nodes[LEN3];
  init(nodes);

  // Read lines
  INT wordCount = readWords(nodes, f_input);
  fclose(f_input);

  // Init navigation structure on the nodes
  initNav(nodes, 0);
  initNav(nodes, 1);
  initNav(nodes, 2);

  INT componentCount = findComponents(nodes, mode & MODE_COMPONENTLIST);

  if (mode & MODE_COMPONENTSTAT) printf("%d components\n", componentCount - 1);

  calcDegrees(nodes, mode & MODE_DEGREESTAT, mode & MODE_DEGREELIST);

  if (mode & MODE_PATH) shortestPath(nodes, a[0]-'a',a[1]-'a',a[2]-'a',b[0]-'a',b[1]-'a',b[2]-'a', TRUE);

  if (mode & MODE_DIAMETER) diameter(fopen(argv[1], "r"), wordCount, nodes);
}
Esempio n. 20
0
LocationID bruteForce(DracView currentView, Map g){
        int distance[4];
        int connections[50];
        int *numLocations;
        int k = 50;
        int *array;
        int trail[6];
       
       
        dracViewPrint (currentView);
       
        giveMeTheTrail(currentView, PLAYER_LORD_GODALMING, trail);
       
        numLocations = &k;
       
        int i = 0;
        int j = 0;
        int l = 0;
       
        int tempDistance = 0;
        int compareDistance = 0;
        LocationID nextMove = -1;
        int isLegalMove = 1;
       
        //Required for brute force
        int path[20];
        int trans[20];
       
        //Finds where Dracula is
        LocationID dracula = whereIs(currentView, PLAYER_DRACULA);
        LocationID hunter1 = whereIs(currentView, PLAYER_LORD_GODALMING);
       
        //Sets all of the values in connections to -1
        for (i = 0; i <= 50; i++) connections[i] = -1;
       
        //Finds the distance between Dracula and all of the other hunters
        //proximity(distance, currentView, dracula); We'll use this later not for now
        compareDistance = 50; //Set an arbitarily big enough number for compareDistance
       
        //Where can Dracula travel by road
        array = whereCanIgo(currentView, numLocations, 1, 0);
       
        for (l = 0; l < 50; l++) {
                connections [l] = array[l];
        }
       
        i = 0;
        if(connections[0] != -1){
                while(connections[i] != -1){
                        //Finds the shortest distance and then puts it on.
                        tempDistance = shortestPath(g, connections[i], hunter1, path, trans);
                        if(compareDistance > tempDistance){
                                for(j = 0; j <= 5; j++){
                                        if (trail[j] == connections[i]) {
                                                isLegalMove = 0;
                                        }      
                                }
                                if(isLegalMove == 1){//If its a legal move change the following.
                                        compareDistance = tempDistance;
                                        nextMove = connections[i];
                                } else {
                                        isLegalMove = 1; // Resets the isLegalMove flag
                                }
                        }
                        i++;
                }
        }
       
        return nextMove;
       
}
Esempio n. 21
0
int main(int argc, char **argv)
{
  t_graph *g = new_graph(6);
  int *d;
  int i, j;
  int **f;
  t_graph *mst;

  add_vertex(g, "s");
  add_vertex(g, "o");
  add_vertex(g, "p");
  add_vertex(g, "q");
  add_vertex(g, "r");
  add_vertex(g, "t");

  add_edge(g, 0, 1, 3);
  add_edge(g, 0, 2, 3);
  add_edge(g, 1, 2, 2);
  add_edge(g, 1, 3, 3);
  add_edge(g, 2, 4, 2);
  add_edge(g, 3, 4, 4);
  add_edge(g, 3, 5, 2);
  add_edge(g, 4, 5, 3);

  dfs(g);
  bfs(g);
  show_am(g);
  show_edges(g);
  d = dijkstra(g, 0);
  for (i = 0; i < g->v; i++)
    {
      if (d[i] != INF)
	printf("%d ",d[i]);
      else
	printf("%s ","I");
    }
  printf("%s", "\n");
  free(d);
  d = shortestPath(g, 0);
  for (i = 0; i < g->v; i++)
    {
      if (d[i] != -1)
	printf("%s ", g->vertices[d[i]].name);
      else
	printf("%s ", "NA");
      printf("%c ",' ');
    }
  printf("%s","\n");
  f = floyd(g);
  for (i = 0; i < g->v; i++)
    {
      for (j = 0; j < g->v; j++)
	{
	  if (f[i][j] != INF)
	    printf("%d", f[i][j]);
	  else
	    printf("%s", "I");
	  printf("%c", ' ');
	}
      printf("%s", " \n");
    }
  free(f);

  //    kruskal and prim should be used on undirected graphs

  printf("\n");
  mst = kruskal(g);

  show_edges(mst);
  free(mst);
  printf("\n\n\n");
  //  //  mst = prim(g, 0);
  //show_edges(mst);
  //free(mst);
  /*
  // FF should only be used on digraphs
  mst = fordFulkerson(g, 0, 5);
  show_am(mst);
  show_edges(mst);
  printf("%s", " \n \n");
  for (i = 0; i < g->v; i++)
    {
      for (j = 0; j < g->v ; j++)
	{
	  if ((i != j) && (g->am[i][j] != INF))
	    {
	      printf("%d ", mst->am[j][i]);
	      printf("%c ",'/');
	      printf("%d ",g->am[i][j]);
	      printf("%c ",' ');
	    }
	  else
	    {
	      printf("%s ", "0/0 ");
	    }
	}
      printf("%s ", " \n ");
    }
    free(mst);*/
  free(g);
  return 0;
}
Esempio n. 22
0
int main()
{
	unsigned long int i, j; /* jokers */
	unsigned long long int k; /* another joker */
	int err;
	
	extern unsigned long int totalNodes; /* declared in loadNGCE.c */
	timexStart();
	node *graph = parseNGCEoutput(GRAPH_PATH, &err); /* create graph */
	if  (graph == NULL)
		return EXIT_FAILURE;
	fprintf(stdout, "Took %4.2f seconds to load graph from file\n", timexGet());

#ifdef COMPUTE_C
	/* computing betweness centrality on cpu */
	fprintf(stdout, "Computing shortest paths and betweeness centrality on cpu, coded in c\n");
	timexStart();
	signed long long int **computedSP = malloc(totalNodes * sizeof(signed long long int *));
	signed long long int pathLength;
	for (i = 0; i < totalNodes; i++)
	{
		computedSP[i] = malloc(totalNodes * sizeof(signed long long int)); /* initialization */
		for (j = 0; j < totalNodes; j++)
		{
			if (i == j)
				computedSP[i][j] = 0; /* 0 distance to self */
			else
				computedSP[i][j] = -1; /* unexplored path */
		}
	}
	
	for (i = 0; i < totalNodes; i++)
		for (j = 0; j < totalNodes; j++)
			if (computedSP[i][j] == -1) /* not known */
			{			
				if ((graph[i].peerCount == 0) || (graph[j].peerCount ==0))
				{} /* oops. no connection */
				else
					pathLength = shortestPath(&graph[i], &graph[j], graph); /* calculate */
				
				computedSP[i][j] = pathLength; /* set this */
				computedSP[j][i] = pathLength; /* and reverse to result */
			}
	fprintf(stdout, "Took %2f seconds to compute shortest paths and betweeness centrality\n", timexGet());
	
	#ifdef DEBUG_OUTPUT
		for (i = 0; i < totalNodes; i++)
			fprintf(stdout, "Node %4lu has a betweeness centrality of %4lu\n", graph[i].name, graph[i].spCount);
	#endif
	
#endif
	
#ifdef COMPUTE_OPENCL
	/* creating all shortest paths-pairs */
	k = 0;
	pair *all = malloc(totalNodes * 3 * sizeof(pair));
	for (i = 0; i < totalNodes; i++)
		for (j = 0; j < totalNodes; j++, k++)
		{
			all[k].a = i;
			all[k].b = j;
		}	
	
	/* choosing compute device */
	cl_device_id *devID = malloc(sizeof(cl_device_id));
	devID = availClDevices(&err);
	
	#ifdef DEBUG_OUTPUT
		clDeviceSpecs info;
		err = getDeviceInfo(&info, devID);
		fprintf(stdout, "%s:%d: Working on: %s %s. Memory: %lluM. Work items: %zu. Compute units: %d. Local memory (cache): %lluM. Maximum malloc: %lluM\n",
			__FILE__, __LINE__, info.vendor, info.name, info.memory/1024/1024, info.workGroupSize, info.compUnits, info.localMemory/1024/1024, info.maxMalloc/1024/1024);
	#endif	
	
	/* demo loading kernel source from text file */
	char *fnSource = readKernelSource(KERNEL_FILE, &err);
	char **kernelSource = malloc(sizeof(char *)); /* opencl bs */
	kernelSource[0] = fnSource;
	if (err != READSOURCE_OK)
	{
		free(graph);
		return EXIT_FAILURE;
	}		
	#ifdef DEBUG_OUTPUT
		fprintf(stdout, "%s:%d: Kernel source code following:\n%s\n", __FILE__, __LINE__, fnSource);
	#endif
	
	/* the context */
	cl_context context;
	context = clCreateContext(0, 1, devID, NULL, NULL, &err);
	if (err != CL_SUCCESS)
	{
		fprintf(stderr, "%s:%d: Error creating context: %s\n", __FILE__, __LINE__, strerrorCL(&err));
		return EXIT_FAILURE;
	}

	/* the command queue */
	cl_command_queue commands;
	commands = clCreateCommandQueue(context, *devID, 0, &err);
    if (!commands)
    {
        fprintf(stderr, "%s:%d: Error creating command queue: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }

	/* the actual program, checking */
	cl_program program;
	program = clCreateProgramWithSource(context, 1, (const char **) kernelSource, NULL, &err);
    if (!program)
    {
        fprintf(stderr, "%s:%d: Error creating program: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }
	
	/* the actual program, building */
	err = clBuildProgram(program, 1, devID, NULL, NULL, NULL); /* clBuildProgam(program, 0, NULL, NULL, NULL, NULL); */
    if (err != CL_SUCCESS)
    {
        size_t len;
        char buffer[2048];
		
        fprintf(stderr, "%s:%d: Error building program executable: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        clGetProgramBuildInfo(program, *devID, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);
        fprintf(stderr, "%s:%d: Build log following: %s\n", __FILE__, __LINE__, buffer);
        return EXIT_FAILURE;
    }
	
	/* the kernel */
	cl_kernel kernel;
	kernel = clCreateKernel(program, "betweeness", &err);
	/* cl_kernel clCreateKernel(cl_program program, const char *kernel_name, cl_int *errcode_ret) */	 
    if (!kernel || err != CL_SUCCESS)
    {
        fprintf(stderr, "%s:%d: Error creating compute kernel: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }

	cl_mem inputGraph;
	cl_mem inputPairs;
    cl_mem outputLengths;
	size_t inputGraphSize = sizeof(node) * totalNodes;
	size_t inputPairsSize = sizeof(pair) * totalNodes * 3;
	size_t outputLengthsSize = sizeof(unsigned long int) * totalNodes;
	inputGraph = clCreateBuffer(context,  CL_MEM_READ_ONLY,  inputGraphSize, NULL, NULL);
	inputPairs = clCreateBuffer(context, CL_MEM_READ_ONLY, inputPairsSize, NULL, NULL);
    outputLengths = clCreateBuffer(context, CL_MEM_WRITE_ONLY, outputLengthsSize, NULL, NULL);
    if (!inputGraph || !inputPairs || !outputLengths)
    {
        fprintf(stderr, "%s:%d: Error allocating device memory: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }    
    
    err = clEnqueueWriteBuffer(commands, inputGraph, CL_TRUE, 0, inputGraphSize, graph, 0, NULL, NULL);
    if (err != CL_SUCCESS)
    {
        fprintf(stderr, "%s:%d: Error writing to source array: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }
	
	err = clEnqueueWriteBuffer(commands, inputPairs, CL_TRUE, 0, inputPairsSize, all, 0, NULL, NULL);
    if (err != CL_SUCCESS)
    {
        fprintf(stderr, "%s:%d: Error writing to source array: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }
	
    err = 0;
    err  = clSetKernelArg(kernel, 0, sizeof(cl_mem), &inputGraph);
	err  = clSetKernelArg(kernel, 1, sizeof(cl_mem), &inputPairs);
    err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &outputLengths);
    err |= clSetKernelArg(kernel, 3, sizeof(unsigned long int), &totalNodes);
    if (err != CL_SUCCESS)
    {
        fprintf(stderr, "%s:%d: Error setting kernela arguments: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }
	
	size_t local;
    err = clGetKernelWorkGroupInfo(kernel, *devID, CL_KERNEL_WORK_GROUP_SIZE, sizeof(local), &local, NULL);
    if (err != CL_SUCCESS)
    {
        fprintf(stderr, "%s:%d: Error retrieving kernel work group info: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }
	
    unsigned long long int global = totalNodes * 3;
    err = clEnqueueNDRangeKernel(commands, kernel, 1, NULL, &global, NULL, 0, NULL, NULL);
    if (err)
    {
		fprintf(stderr, "%s:%d: Error executing kernel: %s\n", __FILE__, __LINE__, strerrorCL(&err));
        return EXIT_FAILURE;
    }
	
    clFinish(commands);
	
	unsigned long int *betw = malloc(totalNodes * sizeof(unsigned long int));
    err = clEnqueueReadBuffer( commands, outputLengths, CL_TRUE, 0, sizeof(unsigned long int) * totalNodes, betw, 0, NULL, NULL );  
    if (err != CL_SUCCESS)
    {
        printf("Error: Failed to read output array! %d\n", err);
        exit(1);
    }
	
	
	for (i = 0; i < totalNodes; i++)
		printf("computed a betweeness centrality of: %lu\n", betw[i]);
		
	free(graph);
	free(devID);
	free(kernelSource);
//	free(computedSP);
#endif
	
	return EXIT_SUCCESS;
}