示例#1
0
	public void addNeighbor(MGraphNode n)
	{
		if (n == null)
			return;
		
		neighbors.Add (n);
	}
示例#2
0
	public void build(Position origin, int[,] movementArray)
	{
		int width, height; //map size

		width = movementArray.GetLength (0);
		height = movementArray.GetLength (1);

		nodeArray = new MGraphNode[width,height];

		//Populating nodeArray
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {

				//if movement cost is 5, we can't walk there, so we don't add it to the graph
				if (movementArray [x, y] == 5) 
					continue;

				nodeArray [x, y] = new MGraphNode (new Position(x, y), movementArray [x, y]);
			}
		}

		MGraphNode curr;

		//Now we add the edges
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {

				curr = nodeArray [x, y];

				if (curr == null)
					continue;

				//Maybe I could create methods for each of these?
				//Maybe I don't even need a graph?
				//top
				if ((y + 1) < height) curr.addNeighbor(nodeArray[x,y+1]);

				//right
				if((x+1) < width) curr.addNeighbor(nodeArray[x+1,y]);

				//bottom
				if(y > 0) curr.addNeighbor(nodeArray[x, y-1]);

				//left
				if(x > 0) curr.addNeighbor(nodeArray[x-1, y]);
			}
		}


		//Last step: get the origin node
		this.origin = nodeArray [origin.x, origin.y];
	}
示例#3
0
	public void Run(MovementGraph graph)
	{
		Stopwatch s = new Stopwatch();

		s.Start ();

		List<MGraphNode> Q = new List<MGraphNode>();		//Set of unvisited nodes
		dist = new Dictionary<MGraphNode, int>();			//Distances to each node, from the origin
		prev = new Dictionary<MGraphNode, MGraphNode>();	//Previous node to each node on the path

		foreach(MGraphNode v in graph.nodeArray)			//initializing sets
		{
			if (v == null)
				continue;
			dist [v] = int.MaxValue;
			prev [v] = null;
			Q.Add (v);							
		}

		dist [graph.origin] = 0;							//distance cost from the origin to the origin

		MGraphNode u;
		int alt;

		while (Q.Count > 0) {
			u = getLowestDistance (Q);						//origin will be selected first
			Q.Remove (u);									//equivalent to visiting the node u

			foreach (MGraphNode v in u.neighbors) {
				if (!Q.Contains (v)) continue; 				//We dont want neighbors that have already been visited

				alt = dist [u] + v.moveCost;

				if(alt < dist[v])							//New shortest path to v was found
				{
					dist [v] = alt;
					prev [v] = u;
				}
			}
		}

		s.Stop ();
		UnityEngine.Debug.Log ("Dijkstra's algorithm just finished taking " + s.ElapsedMilliseconds + " ms");

		origin = graph.origin;
		goal = graph.goal;
	}