本文為原創(chuàng),如需轉(zhuǎn)載,請(qǐng)注明作者和出處,謝謝!
有一根27厘米的細(xì)木桿,在第3厘米、7厘米、11厘米、17厘米、23厘米這五個(gè)位置上各有一只螞蟻。木桿很細(xì),不能同時(shí)通過(guò)一只螞蟻。開始時(shí),螞蟻的頭朝左還是朝右是任意的,它們只會(huì)朝前走或調(diào)頭,但不會(huì)后退。當(dāng)任意兩只螞蟻碰頭時(shí),兩只螞蟻會(huì)同時(shí)調(diào)頭朝反方向走。假設(shè)螞蟻們每秒鐘可以走一厘米的距離。編寫程序,求所有螞蟻都離開木桿的最小時(shí)間和最大時(shí)間。
java實(shí)現(xiàn)代碼
public class test_ant
{
private int[] ants = new int[5];
// 1:左 2:右
private int enumDirection[][] = new int[32][5];
private void initDirection()
{
for (int i = 16, column = 0; i > 0; i = i / 2, column++)
{
int n = 1;
for (int j = 0; j < 32; j++)
{
if((j / i) % 2 == 0)
enumDirection[j][column] = 1;
else
enumDirection[j][column] = 2;
}
}
}
private boolean checkAnts()
{
for (int i = 0; i < 5; i++)
{
if (ants[i] > 0 && ants[i] < 28)
return true;
}
return false;
}
private void changeDirection(int row, int col)
{
if (enumDirection[row][col] == 1)
enumDirection[row][col] = 2;
else
enumDirection[row][col] = 1;
}
public void antClimb()
{
initDirection();
for (int n = 0; n < 32; n++)
{
int seconds = 0;
ants[0] = 3;
ants[1] = 7;
ants[2] = 11;
ants[3] = 17;
ants[4] = 23;
while (checkAnts())
{
seconds++;
for (int i = 0; i < ants.length; i++)
{
if (i < ants.length - 1)
{
// 螞蟻相遇
if ((ants[i] == ants[i + 1])
&& ((enumDirection[n][i] + enumDirection[n][i + 1]) == 3))
{
changeDirection(n, i);
changeDirection(n, i + 1);
}
}
if (enumDirection[n][i] == 1)
ants[i]--;
else
ants[i]++;
}
}
for (int j = 0; j < 5; j++)
System.out.print(enumDirection[n][j]);
System.out.println("");
System.out.println(seconds);
}
}
public static void main(String[] args)
{
new test_ant().antClimb();
}
}
其中ants數(shù)組保存了5只螞蟻當(dāng)前在竿上的位置
enumDirection枚舉了所有的32種初始化方向,1代表向左,2代表向右
最短11秒, 最大25秒
運(yùn)行結(jié)果
11111
23
11112
17
11112
23
11122
11
11112
23
11122
17
11122
23
11222
17
11112
23
11122
21
11122
23
11222
21
11122
23
11222
21
11222
23
12222
21
11112
25
11122
25
11122
25
11222
25
11122
25
11222
25
11222
25
12222
25
11122
25
11222
25
11222
25
12222
25
11222
25
12222
25
12222
25
22222
25
新浪微博:http://t.sina.com.cn/androidguy 昵稱:李寧_Lining