?? findpath.cs
字號:
using System;
using System.Drawing;
using System.Collections.Generic;
namespace Skyiv.Ben.PushBox.Common
{
/// <summary>
/// 尋找最短路線
/// </summary>
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 };
/// <summary>
/// 尋找最短路線
/// </summary>
/// <param name="map">地圖</param>
/// <param name="from">出發點</param>
/// <param name="to">目的地</param>
/// <returns>最短路線</returns>
public static Queue<Direction> Seek(byte[,] map, Point from, Point to)
{
Queue<Direction> moveQueue = new Queue<Direction>(); // 路線
int value; // 與離目的地距離相關的一個量,變化規律: ... => 2 => 1 => 3 => 2 => 1 => 3 => 2 => 1
if (Seek(map, to, out value)) // 找到了一條路線
{
Point here = from; // 出發點(即工人的位置)
Point nbr = new Point(); // 四周的鄰居
for (value = (value + 1) % 3 + 1; here != to; value = (value + 1) % 3 + 1) // 逐步走向目的地
{
for (int i = 0; i < offsets.Length; i++)
{
nbr = Fcl.Add(here, offsets[i]); // 開始尋找四周的鄰居
{
moveQueue.Enqueue(directions[i]); // 路線向目的地延伸一步
break;
}
}
here = nbr; // 繼續前進
}
}
Block.CleanAllMark(map); // 清除所有標志,恢復現場
return moveQueue; // 所尋找的路線,如果無法到達目的地則為該路線的長度為零
}
/// <summary>
/// 尋找最短路線,使用廣度優先搜索
/// </summary>
/// <param name="map">地圖</param>
/// <param name="to">目的地</param>
/// <param name="value">輸出:搜索完成時標記的值</param>
/// <returns>是否成功</returns>
static bool Seek(byte[,] map, Point to, out int value)
{
Queue<Point> q = new Queue<Point>();
Block.Mark(ref map[to.Y, to.X], 1); // 從目的地開始往回尋找出發點,目的地標記為1
Point nbr = Point.Empty; // 四周的鄰居
for (; ; )
{
value = Block.Value(map[to.Y, to.X]) % 3 + 1; // 與離目的地距離相關的一個量,用作標記,變化規律:
for (int i = 0; i < offsets.Length; i++) // 1 => 2 => 3 => 1 => 2 => 3 => 1 => 2 => 3 => ...
{
nbr = Fcl.Add(to, offsets[i]); // 開始尋找四周的鄰居
if (Block.IsMan(map[nbr.Y, nbr.X])) break; // 到達出發點(即工人的位置)
if (Block.IsBlank(map[nbr.Y, nbr.X])) // 可以走的路
{
Block.Mark(ref map[nbr.Y, nbr.X], value); // 標記,防止以后再走這條路
q.Enqueue(nbr); // 加入隊列,等待以后繼續尋找
}
}
if (Block.IsMan(map[nbr.Y, nbr.X])) break; // 到達出發點
if (q.Count == 0) return false; // 無法到達出發點
to = q.Dequeue(); // 出隊,繼續尋找,這是廣度優先搜索,因為前面已經把四周能夠走的路全部加入隊列中了.
}
return true; // 找到一條路線
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -