比较重量

小明陪小红去看钻石,他们从一堆钻石中随机抽取两颗并比较她们的重量。这些钻石的重量各不相同。在他们们比较了一段时间后,它们看中了两颗钻石g1和g2。现在请你根据之前比较的信息判断这两颗钻石的哪颗更重。 

给定两颗钻石的编号g1,g2,编号从1开始,同时给定关系数组vector,其中元素为一些二元组,第一个元素为一次比较中较重的钻石的编号,第二个元素为较轻的钻石的编号。最后给定之前的比较次数n。请返回这两颗钻石的关系,若g1更重返回1,g2更重返回-1,无法判断返回0。输入数据保证合法,不会有矛盾情况出现。

测试样例:
2,3,[[1,2],[2,4],[1,3],[4,3]],4
返回:
1

算法思想:转化为图的遍历

代码:

 1 import java.util.*;
 2 
 3 public class Cmp {
 4     public int cmp(int g1, int g2, int[][] records, int n) {
 5         
 6         HashMap<Integer, Node> nodeMap = new HashMap<Integer, Node>();
 7         for(int i = 0; i < records.length; i++) {
 8             if(!nodeMap.containsKey(records[i][0])) {
 9                 nodeMap.put(records[i][0], new Node());
10             }
11             if(!nodeMap.containsKey(records[i][1])) {
12                 nodeMap.put(records[i][1], new Node());
13             }
14             
15             nodeMap.get(records[i][0]).list.add(nodeMap.get(records[i][1]));
16         }
17         
18         Node start = nodeMap.get(g1);
19         Node end = nodeMap.get(g2);
20         
21         if(start == null || end == null) {
22             return 0;
23         }
24         
25         if(recurse(start, end, new HashSet<Node>()))
26             return 1;
27         else if(recurse(end, start, new HashSet<Node>()))
28             return -1;
29         else
30             return 0;
31         
32     }
33     
34     private boolean recurse(Node start, Node end, HashSet<Node> path) {
35         
36         if(path.contains(start)) 
37             return false;
38         else
39             path.add(start);
40         
41         if(start == null)
42             return false;
43         
44         if(start == end)
45             return true;
46         
47         for(Node n : start.list) {
48             if(recurse(n, end, path)) {
49                 return true;
50             }
51         }
52         return false;
53     }
54 }
55 
56 class Node {
57     public ArrayList<Node> list = new ArrayList<Node> ();
58 }

 



posted @ 2016-08-21 07:29  DavieTiming  阅读(387)  评论(0编辑  收藏  举报