码迷,mamicode.com
首页 > 编程语言 > 详细

倒水问题(Java)

时间:2019-08-22 00:32:30      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:问题   code   arraylist   span   ISE   div   main   lin   ati   

有两个杯子,一个杯子容量为3,另一个容量为5.  怎么倒水才能得到体积为4的水.

可以给一个杯子加满水、或倒光、或把一个杯子的水加到另一个杯子中.

 1 import java.util.ArrayList;
 2 import java.util.Collections;
 3 import java.util.LinkedList;
 4 import java.util.Queue;
 5 
 6 import static java.lang.Integer.min;
 7 
 8 public class WaterPuzzle {
 9 
10     private int[] pre;
11     private int end;
12 
13     public WaterPuzzle() {
14         boolean[] visited = new boolean[100];
15         pre = new int[100];
16         end = -1;
17         // BFS
18         Queue<Integer> queue = new LinkedList<>();
19         queue.add(0);
20         visited[0] = true;
21         while (!queue.isEmpty()) {
22             int cur = queue.remove();
23             int a = cur / 10;
24             int b = cur % 10;
25 
26             ArrayList<Integer> nexts = new ArrayList<>();
27             nexts.add(5 * 10 + b);
28             nexts.add(a * 10 + 3);
29             nexts.add(a * 10 + 0);
30             nexts.add(0 * 10 + b);
31 
32             int IN = min(3 - b, a);
33             nexts.add((a - IN) * 10 + b + IN);
34             IN = min(5 - a, b);
35             nexts.add((a + IN) * 10 + b - IN);
36 
37             for (int next : nexts) {
38                 if (!visited[next]) {
39                     visited[next] = true;
40                     queue.add(next);
41                     pre[next] = cur;
42                     if (next / 10 == 4 || next % 10 == 4) {
43                         end = next;
44                         return;
45                     }
46                 }
47             }
48         }
49     }
50 
51     public Iterable<Integer> result() {
52         ArrayList<Integer> ans = new ArrayList<>();
53         if (end == -1)
54             return ans;
55         int p = end;
56         while (p != 0) {
57             ans.add(p);
58             p = pre[p];
59         }
60         ans.add(0);
61         Collections.reverse(ans);
62         return ans;
63     }
64 
65     public static void main(String[] args) {
66         System.out.println(new WaterPuzzle().result());
67     }
68 }

 

倒水问题(Java)

标签:问题   code   arraylist   span   ISE   div   main   lin   ati   

原文地址:https://www.cnblogs.com/AntonLiu/p/11391973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!