首页 > 快乐分享 > 5只蚂蚁走木棍问题的非递归解法(java实现)[百度面试题]

5只蚂蚁走木棍问题的非递归解法(java实现)[百度面试题]

2009年6月30日 浏览:126

题目描述
有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。木杆很细,不能同时通过一只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。编写程序,求所有蚂蚁都离开木杆的最小时间和最大时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.leochan;  
 
 public class DirectAntWalker {  
 
 public static int totalLength = 27;  
 
 public static void main(String[] args) {  
 
 directTest();  
 
 }  
 
 private static void directTest() {  
 int count = 0;  
 for (int d1 = -1; d1 <= 1; d1 += 2) {  
 for (int d2 = -1; d2 <= 1; d2 += 2) {  
 for (int d3 = -1; d3 <= 1; d3 += 2) {  
 for (int d4 = -1; d4 <= 1; d4 += 2) {  
 for (int d5 = -1; d5 <= 1; d5 += 2) {  
 
 count++;  
 
 // 构造蚂蚁数组  
 int[] ants = { 3 * d1, 7 * d2, 11 * d3, 17 * d4,  
 23 * d5 };  
 
 // 设置index初始取值范围  
 int idx1 = 0, idx2 = 4;  
 int totalTime = 0;  
 
 int i = 0;  
 while (true) {  
 
 // 如果有蚂蚁先达到边界,一定是发生在边界处  
 // 如果第一只蚂蚁已经达到边界,就忽略这只蚂蚁  
 if (ants[idx1] == 0  
 || ants[idx1] == totalLength) {  
 idx1++;  
 }  
 // 如果最后一只蚂蚁已经达到边界,就忽略这只蚂蚁  
 if (ants[idx2] == 0  
 || ants[idx2] == totalLength) {  
 idx2--;  
 }  
 // 如果当前可访问的下界超过上界,就跳出循环  
 if (idx1 > idx2)  
 break;  
 // 如果下届等于上界,则说明仅有一只蚂蚁还没有走出去。  
 else if (idx1 == idx2) {  
 if (ants[idx1] < 0) {  
 totalTime -= ants[idx1];  
 } else {  
 totalTime += (totalLength - ants[idx1]);  
 }  
 break;  
 }  
 
 // 对于其他情况让 所有的蚂蚁走一步,如果出现了蚂蚁位置重合,就让重合的2只蚂蚁转向  
 
 ants[idx1] = ants[idx1] + 1;  
 for (i = idx1 + 1; i <= idx2; i++) {  
 ants[i] = ants[i] + 1;  
 if (ants[i] + ants[i - 1] == 0) {  
 ants[i] *= -1;  
 ants[i - 1] *= -1;  
 }  
 }  
 
 // 消耗的时间递增1。  
 totalTime++;  
 }  
 
 System.out.print("count=" + count + " d1=" + d1  
 + " d2=" + d2 + " d3=" + d3 + " d4=" + d4  
 + " d5=" + d5);  
 System.out.println("  totalTime=" + totalTime);  
 }  
 }  
 }  
 }  
 }  
 }  
 }
声明: 转载本博原创文章请注明 文章转载自: 灰狼博客, 原文地址:5只蚂蚁走木棍问题的非递归解法(java实现)[百度面试题]
  1. 2009年7月1日14:50 | #1

    程序这玩意 我只看得懂~自己搞不定 呵呵

  2. 2009年7月3日10:01 | #2

    @Sean
    我对Java更菜…只是没事讨论一下.

  1. 本文目前尚无任何 trackbacks 和 pingbacks.

注意:评论者允许使用'@user空格'的方式将自己的评论通知另外评论者。例如,ABC是本文的评论者之一,则使用'@ABC '(不包括单引号)将会自动将您的评论发送给ABC.请务必注意user必须和评论者名相匹配(大小写一致).