我需要找到一个循环开始和结束在给定点。不能保证它存在。 我使用bool[,] points
来指示哪个点可以在循环中。 Poins只能在网格上。 points
指示网格上的给定点是否可以循环。 我需要使用最少的点数来找到这个循环。 一点只能使用一次。 连接只能是垂直或水平。周期寻找算法
让这成为我们的点(红色起点):
去除死皮ImageShack的链接
我意识到,我可以这样做:
while(numberOfPointsChanged)
{
//remove points that are alone in row or column
}
所以我有:
删除死ImageShack链接
现在,我可以找到路径。
去除死皮ImageShack的链接
但是,如果有不是由这个循环删除,但不应该在路径点?
我已经写代码:
class MyPoint
{
public int X { get; set; }
public int Y { get; set; }
public List<MyPoint> Neighbours = new List<MyPoint>();
public MyPoint parent = null;
public bool marked = false;
}
private static MyPoint LoopSearch2(bool[,] mask, int supIndexStart, int recIndexStart)
{
List<MyPoint> points = new List<MyPoint>();
//here begins translation bool[,] to list of points
points.Add(new MyPoint { X = recIndexStart, Y = supIndexStart });
for (int i = 0; i < mask.GetLength(0); i++)
{
for (int j = 0; j < mask.GetLength(1); j++)
{
if (mask[i, j])
{
points.Add(new MyPoint { X = j, Y = i });
}
}
}
for (int i = 0; i < points.Count; i++)
{
for (int j = 0; j < points.Count; j++)
{
if (i != j)
{
if (points[i].X == points[j].X || points[i].Y == points[j].Y)
{
points[i].Neighbours.Add(points[j]);
}
}
}
}
//end of translating
List<MyPoint> queue = new List<MyPoint>();
MyPoint start = (points[0]); //beginning point
start.marked = true; //it is marked
MyPoint last=null; //last point. this will be returned
queue.Add(points[0]);
while(queue.Count>0)
{
MyPoint current = queue.First(); //taking point from queue
queue.Remove(current); //removing it
foreach(MyPoint neighbour in current.Neighbours) //checking Neighbours
{
if (!neighbour.marked) //in neighbour isn't marked adding it to queue
{
neighbour.marked = true;
neighbour.parent = current;
queue.Add(neighbour);
}
//if neighbour is marked checking if it is startig point and if neighbour's parent is current point. if it is not that means that loop already got here so we start searching parents to got to starting point
else if(!neighbour.Equals(start) && !neighbour.parent.Equals(current))
{
current = neighbour;
while(true)
{
if (current.parent.Equals(start))
{
last = current;
break;
}
else
current = current.parent;
}
break;
}
}
}
return last;
}
但它不工作。它创建的路径包含两点:开始和它的第一个邻居。
我在做什么错?
编辑: 忘了提...横向连接后,必须有垂直,水平,垂直等... 更重要的是每行和每列有需要是最大的两个点(两个或没有)在周期中。但是这种情况与“周期必须是最短的周期”是一样的。
你所说的“循环”在图论中通常被称为“循环”(在我看过你的照片之前,“循环”的含义并不完全清楚)。我编辑了适当的问题,使其易于理解。仍然不清楚你的点如何存储在二维布尔数组中。 – 2010-12-19 14:25:20
编辑,以澄清我如何存储积分。 – 2010-12-19 14:34:48
这不是C#的问题,仅仅是关于算法的问题。 – 2010-12-19 14:38:52