In the article "using C # to develop smartphone software: Push box (c)", I made a general introduction to the Push box program. In this article, the Common/findpath.cs source program file is introduced.
The following is a reference fragment:
using System;
using System.Drawing;
using System.Collections.Generic;
namespace Skyiv.Ben.PushBox.Common
{
///
///to find the shortest route
///
Static Class Findpath
{
static size[] offsets = {New Size (0, 1), New size (1, 0), new size (0,-1), New size (-1, 0)};
static direction[] Directions = {Direction.south, direction.east, Direction.north, direction.west};
///
///to find the shortest route
///
///Map
///starting point
///Destination
///Shortest Route
public static Queue Seek (ushort[,] map, point from, point to)
{
Queue movequeue = new Queue (); Route
int value; Distance from Destination
if (Seek (map, to, out value))//found a route
{
point here = from; Starting point (i.e. the position of the worker)
point NBR = new Point (); Four-week neighbor
.
for (value--value > 0; value--)//step towards destination
{
for (int i = 0; i < offsets. Length; i++)
{
NBR = Fcl.add (here, offsets[i]); Start looking around for neighbors
if (Block.value MAP[NBR. Y, NBR. X] = = value)//Just go in this direction
{
Movequeue.enqueue (Directions[i]); The route extends to the destination
break;
}
}
here = NBR; Keep moving,
.
}
}
Block.cleanallmark (map); Clear all signs, restore the scene
return movequeue; The route being sought, if the destination is not reached, the length of the route is zero
}
///
///Find the shortest route, use breadth First search
///
///Map
///Destination
///Output: Length of route (plus 1)
///is successful
static bool Seek (ushort[,] map, point to, out int value)
{
Queue q = new Queue ();
Block.mark (ref map[to. Y, to. X], 1); Start looking back from your destination and mark your destination as 1
point NBR = Point.empty; Four-week neighbor
.
for (;;)
{
value = Block.value (map[to. Y, to. X]) + 1; Distance from destination (plus 1), used as marker
for (int i = 0; i < offsets. Length; i++)
{
NBR = Fcl.add (To, offsets[i]); Start looking around for neighbors
if (Block.isman MAP[NBR. Y, NBR. X])) break; Arrive at the starting point (i.e. the position of the worker)
if (Block.isblank MAP[NBR. Y, NBR. X])///can go the road
{
Block.mark (ref MAP[NBR. Y, NBR. X], value); Mark, prevent the road from coming again
Q.enqueue (NBR); Join the queue, wait to continue looking for
}
}
if (Block.isman MAP[NBR. Y, NBR. X])) break; Reach the starting point
if (Q.count = = 0) return false; Unable to reach the starting point
to = Q.dequeue (); Out team, keep looking, this is breadth first search, because the front has been able to walk around all the way to join the queue.
}
return true; Find a route
}
}
}