读书人

田鸡过河

发布时间: 2013-11-06 16:26:37 作者: rapoo

青蛙过河
今天在数上看到一个题目
一个青蛙过河程序 总是调试错误 请牛人帮忙
题目:一条小溪上7块石头,如图所示:(图就是下面的链接)
http://album.hi.csdn.net/app_uploads/jinder22/20081220/235450716.p.jpg?d=20081220235510403
分别有六只青蛙:A,B,C,D,E,F。A,B,C三只蛙想去右岸,它们只会从左向右跳;D,E,F三只蛙想去左岸,它们只会从右向左跳。青蛙每次最多跳到自己前方第2块石头上。请问最少要跳几次所有青蛙上岸。写出步骤。
参考了一段代码,不是很明白Move这个func的思路.可不可以解释一下


class Program
{
static void Main(string[] args)
{
int[] begintArray = new int[] { 1, 1, 1, 0, 2, 2, 2 };
int[] endArray = new int[] { 2, 2, 2, 0, 1, 1, 1 };

//最后的解,最先移动的排在最后
List<string> jumpStep = new List<string>();
jump(begintArray, endArray, jumpStep);

//反转一下得到正序的解
jumpStep.Reverse();
foreach (string step in jumpStep)
Console.WriteLine(step);
}

private static int[] Move(int[] beginArr, int zeroIndex)
{
List<int> moveTo=new List<int>();
if (zeroIndex >= 1 && beginArr[zeroIndex - 1] == 1)
{
moveTo.Add(zeroIndex-1);
}
if (zeroIndex >= 2 && beginArr[zeroIndex - 2] == 1)
{
moveTo.Add(zeroIndex-2);
}
if (zeroIndex < beginArr.Length - 1 && beginArr[zeroIndex + 1] == 2)
{
moveTo.Add(zeroIndex + 1);
}
if (zeroIndex < beginArr.Length - 2 && beginArr[zeroIndex + 2] == 2)
{
moveTo.Add(zeroIndex + 2);
}
return moveTo.ToArray();

}
private static bool CompareArray(int[] begintArray, int[] endArray)
{
for (int i = 0; i < begintArray.Length; i++)
{
if (begintArray[i] != endArray[i])
return false;
}
return true;
}

private static bool jump(int[] begintArray, int[] endArray, List<string> jumpStep)
{
if (CompareArray(begintArray, endArray))
return true;
int zeroIndex = Array.IndexOf(begintArray, 0);
int[] moveTo = Move(begintArray, zeroIndex);


//穷举所有可以移动的位置
foreach (int moveStep in moveTo)
{
int[] newBegin = (int[])begintArray.Clone();
newBegin[zeroIndex] = newBegin[moveStep];
newBegin[moveStep] = 0;
if (jump(newBegin, endArray, jumpStep))
{
string steplog = "";
for (int i = 0; i < newBegin.Length; i++)
steplog += newBegin[i].ToString();
jumpStep.Add(steplog);
return true;
}
}
return false;
}
}



[解决办法]
move的思路就是把能移动到空位的位置记录下来供枚举用。

private static int[] Move(int[] beginArr, int zeroIndex)
{ // beginArr保存了当前的青蛙的位置, zeroIndex是空位的位置
List<int> moveTo=new List<int>();
if (zeroIndex >= 1 && beginArr[zeroIndex - 1] == 1)
{ // 如果距离空位左边1块石头的青蛙是A/B/C,可以跳到空位
moveTo.Add(zeroIndex-1);
}
if (zeroIndex >= 2 && beginArr[zeroIndex - 2] == 1)
{ // 如果距离空位左边2块石头的青蛙是A/B/C,可以跳到空位
moveTo.Add(zeroIndex-2);
}
if (zeroIndex < beginArr.Length - 1 && beginArr[zeroIndex + 1] == 2)
{ // 如果距离空位右边1块石头的青蛙是D/E/F,可以跳到空位
moveTo.Add(zeroIndex + 1);
}
if (zeroIndex < beginArr.Length - 2 && beginArr[zeroIndex + 2] == 2)
{ // 如果距离A/B/C块石头的青蛙是D/E/F,可以跳到空位
moveTo.Add(zeroIndex + 2);
}
return moveTo.ToArray();

}

[解决办法]
http://alphaxiang.wikispaces.com/%E9%9D%92%E8%9B%99%E6%8D%A2%E4%BD%8D%E9%97%AE%E9%A2%98

哈哈,我也写了一个这个问题的程序

读书人网 >软件架构设计

热点推荐